Skip to content

HTTPException

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

抛出 HTTPException

你可以通过指定状态码并设置消息或自定义响应来主动抛出 HTTPException

自定义消息

对于简单的 text 响应,只需设置错误的 message

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

自定义 Response

如需返回其他类型的响应或设置响应头,可以使用 res 选项。注意:构造函数中传入的状态码将用于生成响应。

ts
import { 
HTTPException
} from 'hono/http-exception'
const
errorResponse
= new
Response
('未授权', {
status
: 401, // 这里的状态码会被忽略
headers
: {
Authenticate
: 'error="invalid_token"',
}, }) throw new
HTTPException
(401, {
res
:
errorResponse
})

错误原因(Cause)

无论哪种方式,你都可以使用 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
((
error
,
c
) => {
if (
error
instanceof
HTTPException
) {
console
.
error
(
error
.
cause
)
// 获取自定义响应 return
error
.
getResponse
()
} // ... })

WARNING

HTTPException.getResponse 并不会读取 Context。如果需要包含 Context 中已设置的响应头,需要手动将它们合并到新的 Response 中。

Released under the MIT License.