错误处理
js
import { HTTPException } from "hono/http-exception";
throw new HTTPException(401, { message: "自定义错误信息" });如:
ts
app.post("/auth", async (c, next) => {
// 身份验证
if (authorized === false) {
throw new HTTPException(401, { message: "自定义错误信息" });
}
await next();
});也可以自定义响应
ts
const errorResponse = new Response("未经授权", {
status: 401,
headers: {
Authenticate: 'error="invalid_token"',
},
});
throw new HTTPException(401, { res: errorResponse });全局响应
ts
app.onError((err, c) => {
if (err instanceof HTTPException) {
// 获取自定义响应
return err.getResponse();
}
});