Exception(异常)
当发生致命错误(如认证失败)时,必须抛出 HTTPException。
throw HTTPException
下面的例子展示了如何在中间件中抛出 HTTPException:
import { HTTPException } from 'hono/http-exception'// ...app.post('/auth', async (c, next) => {// 执行认证if (authorized === false) {throw new HTTPException(401, { message: 'Custom error message' })}await next()})
你也可以自定义返回给用户的 Response:
import { HTTPException } from 'hono/http-exception'const errorResponse = new Response('Unauthorized', {status: 401,headers: {Authenticate: 'error="invalid_token"',},})throw new HTTPException(401, { res: errorResponse })
Handling HTTPException
你可以通过 app.onError 处理抛出的 HTTPException:
import { HTTPException } from 'hono/http-exception'// ...app.onError((err, c) => {if (err instanceof HTTPException) {// 获取自定义的 Responsereturn err.getResponse()}// ...})
cause
cause 选项允许添加 cause 数据,用于错误链路追踪:
app.post('/auth', async (c, next) => {try {authorize(c)} catch (e) {throw new HTTPException(401, { message, cause: e })}await next()})
