跳到主要内容

响应与错误

响应怎么构造,状态码与头怎么写?​

  • 返回值即响应: c.text、c.json、c.html、c.body 产出对应 Content-Type;
  • c.redirect(url, 301): 默认是 302;
  • c.notFound(): 交给 app.notFound;
  • 写法一: 先 c.status() 或 c.header(), 再 return;
  • 写法二: 一次传给 c.json(body, status, headers);
  • 约束: c.header() 必须在 return 之前;
app.post("/posts", (c) => {
c.status(201);
c.header("X-Message", "created");
return c.json({ ok: true });
});

app.post("/posts2", (c) => c.json({ ok: true }, 201, { "X-Message": "created" }));
app.get("/bin", (c) =>
c.body(new Uint8Array([0x48]), 200, { "Content-Type": "application/octet-stream" }),
);
  • 有类型安全客户端时失败一律 return c.json(..., status), 客户端才推得出错误体类型;

已经生成的响应还能改吗?​

  • 时机: 只能在 await next() 之后;
  • 追加头: 用 c.res.headers.append;
  • 整体替换: 先 c.res = undefined 再赋值, 旧响应头除 content-type 外保留;
app.use(async (c, next) => {
await next();
c.res.headers.append("X-Debug", "1");
});
  • 流式响应一旦开始写就改不了;

抛出的异常最后去哪,该抛什么?​

  • 异常处理: 一律交给 app.onError, 没写则自动 500;
  • 中间件: 读 c.error 记日志, 不要重复返回响应;
  • 预期内错误: 直接 return c.json(..., 4xx);
  • 深层 Service 或第三方库: 抛 HTTPException;
  • 不可恢复的程序错误: 抛普通 Error;
import { HTTPException } from "hono/http-exception";

app.onError((err, c) => {
if (err instanceof HTTPException) return err.getResponse();
console.error(err);
return c.json({ ok: false, error: "internal_error" }, 500);
});

// 自定义响应体;或用 { message, cause } 保留原始错误
throw new HTTPException(401, { res: new Response("Unauthorized") });

HTTPException 与 404 怎么处理?​

  • HTTPException: 状态码以构造参数为准, res 里的 status 被忽略;
  • getResponse(): 不带 c.header() 设过的头;
  • 边界: 流式响应内不可用;

404 与 405 怎么处理?​

  • 404 处理: app.notFound((c) => c.json({ ok: false, error: "not_found" }, 404));
  • 生效范围: 只有顶层应用;
  • 方法不对: 默认也是 404, 要 405 需挂 methodNotAllowed({ app });