Appearance
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 a 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 处理未捕获的 HTTPException。它们包含一个 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((error, c) => {
if (error instanceof HTTPException) {
console.error(error.cause)
// Get the custom response
return error.getResponse()
}
// ...
})警告
HTTPException.getResponse 无法感知 Context。要包含已在 Context 中设置的标头,你必须将它们应用于新的 Response。
¥HTTPException.getResponse is not aware of Context. To include headers already set in Context, you must apply them to a new Response.