Exception(异常)

当发生致命错误(如认证失败)时,必须抛出 HTTPException

throw HTTPException

下面的例子展示了如何在中间件中抛出 HTTPException

  1. import { HTTPException } from 'hono/http-exception'
  2. // ...
  3. app.post('/auth', async (c, next) => {
  4. // 执行认证
  5. if (authorized === false) {
  6. throw new HTTPException(401, { message: 'Custom error message' })
  7. }
  8. await next()
  9. })

你也可以自定义返回给用户的 Response:

  1. import { HTTPException } from 'hono/http-exception'
  2. const errorResponse = new Response('Unauthorized', {
  3. status: 401,
  4. headers: {
  5. Authenticate: 'error="invalid_token"',
  6. },
  7. })
  8. throw new HTTPException(401, { res: errorResponse })

Handling HTTPException

你可以通过 app.onError 处理抛出的 HTTPException

  1. import { HTTPException } from 'hono/http-exception'
  2. // ...
  3. app.onError((err, c) => {
  4. if (err instanceof HTTPException) {
  5. // 获取自定义的 Response
  6. return err.getResponse()
  7. }
  8. // ...
  9. })

cause

cause 选项允许添加 cause 数据,用于错误链路追踪:

  1. app.post('/auth', async (c, next) => {
  2. try {
  3. authorize(c)
  4. } catch (e) {
  5. throw new HTTPException(401, { message, cause: e })
  6. }
  7. await next()
  8. })