跳转到正文

HTTPException ​

发生严重错误时,Hono(以及生态中的许多中间件)可能会抛出 HTTPException。这是 Hono 自定义的 Error,用于简化返回错误响应的过程。

抛出 HTTPException ​

指定状态码,并提供消息或自定义响应,就可以抛出自己的 HTTPException。

自定义消息 ​

对于基本的 text 响应,只需设置错误的 message。

ts
import { 
HTTPException
} from 'hono/http-exception'
throw new
HTTPException
(401, {
message
: 'Unauthorized' })

自定义响应 ​

对于其他类型的响应,或需要设置响应头时,请使用 res 选项。请注意,创建响应时使用的是传入构造函数的状态码。

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 选项向 HTTPException 添加任意数据。

ts
app
.
post
('/login', async (
c
) => {
try { await
authorize
(
c
)
} catch (
cause
) {
throw new
HTTPException
(401, {
message
,
cause
})
} return
c
.
redirect
('/')
})

处理 HTTPException ​

可以使用 app.onError 处理未捕获的 HTTPException。它提供 getResponse 方法,根据错误的 status,以及错误的 message 或抛出错误时设置的自定义响应,创建并返回一个新的 Response。

ts
import { 
HTTPException
} from 'hono/http-exception'
// ...
app
.
onError
((
err
,
c
) => {
if (
err
instanceof
HTTPException
) {
// Return the error response generated by HTTPException return
err
.
getResponse
()
} // For any other unexpected errors, log and return a generic 500 response
console
.
error
(
err
)
return
c
.
text
('Internal Server Error', 500)
})

注意

HTTPException.getResponse 不会读取 Context。要包含已在 Context 中设置的响应头,必须将它们应用到新的 Response 上。

基于 MIT 许可证发布。