跳至內容

例外

當發生致命錯誤時,例如身份驗證失敗,必須拋出 HTTPException。

throw 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

您可以使用 app.onError 來處理拋出的 HTTPException。

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

以 MIT 授權條款發布。