Skip to content

异常

¥Exception

当发生致命错误(例如身份验证失败)时,必须抛出 HTTPException。

¥When a fatal error occurs, such as authentication failure, an HTTPException must be thrown.

抛出 HTTPException

¥throw HTTPException

此示例从中间件抛出 HTTPException。

¥This example throws an HTTPException from the middleware.

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
()
})

你可以指定要返回给用户的响应。

¥You can specify the response to be returned back to the user.

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

¥Handling HTTPException

你可以使用 app.onError 处理抛出的 HTTPException。

¥You can handle the thrown HTTPException with 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 数据。

¥The cause option is available to add a cause data.

ts
app
.
post
('/auth', async (
c
,
next
) => {
try {
authorize
(
c
)
} catch (
e
) {
throw new
HTTPException
(401, {
message
,
cause
:
e
})
} await
next
()
})

Hono v4.7 中文网 - 粤ICP备13048890号