例外
認証失敗などの致命的なエラーが発生した場合は、HTTPExceptionをスローする必要があります。
HTTPExceptionをスローする
この例では、ミドルウェアからHTTPExceptionがスローされます。
ts
import { HTTPException } from 'hono/http-exception'
// ...
app.post('/auth', async (c, next) => {
// authentication
if (authorized === false) {
throw new HTTPException(401, { message: 'Custom error message' })
}
await next()
})
ユーザーに返されるレスポンスを指定できます。
ts
import { HTTPException } from 'hono/http-exception'
const errorResponse = new Response('Unauthorized', {
status: 401,
headers: {
Authenticate: 'error="invalid_token"',
},
})
throw new HTTPException(401, { res: errorResponse })
HTTPExceptionの処理
スローされたHTTPExceptionはapp.onError
で処理できます。
ts
import { HTTPException } from 'hono/http-exception'
// ...
app.onError((err, c) => {
if (err instanceof HTTPException) {
// Get the custom response
return err.getResponse()
}
// ...
})
cause
cause
オプションを使用すると、cause
データを追加できます。
ts
app.post('/auth', async (c, next) => {
try {
authorize(c)
} catch (e) {
throw new HTTPException(401, { message, cause: e })
}
await next()
})