Skip to content

HTTP异常

🌐 HTTPException

当发生致命错误时,Hono(以及许多生态系统中间件)可能会抛出 HTTPException。这是一个自定义的 Hono Error,它简化了 返回错误响应 的过程。

🌐 When a fatal error occurs, Hono (and many ecosystem middleware) may throw an HTTPException. This is a custom Hono Error that simplifies returning error responses.

抛出 HTTPExceptions

🌐 Throwing HTTPExceptions

你可以通过指定状态码以及消息或自定义响应来抛出你自己的 HTTPException。

🌐 You can throw your own HTTPExceptions by specifying a status code, and either a message or a custom response.

自定义消息

🌐 Custom Message

对于基本的 text 响应,只需设置错误 message

🌐 For basic text responses, just set the error message.

ts
import { 
HTTPException
} from 'hono/http-exception'
throw new
HTTPException
(401, {
message
: 'Unauthorized' })

自定义响应

🌐 Custom Response

对于其他响应类型,或设置响应头,请使用 res 选项。请注意,传递给构造函数的状态是用于创建响应的状态。

🌐 For other response types, or to set response headers, use the res option. Note that the status passed to the constructor is the one used to create responses.

ts
import { 
HTTPException
} from 'hono/http-exception'
const
errorResponse
= new
Response
('Unauthorized', {
status
: 401, // this gets ignored
headers
: {
Authenticate
: 'error="invalid_token"',
}, }) throw new
HTTPException
(401, {
res
:
errorResponse
})

原因

🌐 Cause

在任何情况下,你都可以使用 cause 选项向 HTTPException 添加任意数据。

🌐 In either case, you can use the cause option to add arbitrary data to the HTTPException.

ts
app
.
post
('/login', async (
c
) => {
try { await
authorize
(
c
)
} catch (
cause
) {
throw new
HTTPException
(401, {
message
,
cause
})
} return
c
.
redirect
('/')
})

处理 HTTPExceptions

🌐 Handling HTTPExceptions

你可以使用 app.onError 处理未捕获的 HTTPExceptions。它们包括一个 getResponse 方法,该方法返回一个由错误 status 创建的新 Response,以及错误 message 或在抛出错误时设置的 自定义响应

🌐 You can handle uncaught HTTPExceptions with app.onError. They include a getResponse method that returns a new Response created from the error status, and either the error message, or the custom response set when the error was thrown.

ts
import { 
HTTPException
} from 'hono/http-exception'
// ...
app
.
onError
((
err
,
c
) => {
if (
err
instanceof
HTTPException
) {
// Return the error response generated by HTTPException return
err
.
getResponse
()
} // For any other unexpected errors, log and return a generic 500 response
console
.
error
(
err
)
return
c
.
text
('Internal Server Error', 500)
})

WARNING

HTTPException.getResponse 不知道 Context。要包含已经在 Context 中设置的标题,必须将它们应用到新的 Response 上。

Hono 中文网 - 粤ICP备13048890号