import { test } from "node:test"; import assert from "node:assert/strict"; import { createErrorMiddleware } from "../app.js"; function createCtx() { return { method: "POST", path: "/health/test", headerSent: false, status: 200, body: null, headers: {}, set(name, value) { this.headers[name] = value; }, }; } test("非法 JSON 等 4xx 异常统一转成业务码", async () => { const ctx = createCtx(); const err = new Error("invalid JSON, only supports object and array"); err.status = 400; err.type = "entity.parse.failed"; await createErrorMiddleware()(ctx, async () => { throw err; }); assert.equal(ctx.status, 200); assert.equal(ctx.body.code, 400); assert.equal(ctx.body.msg, "请求参数格式不正确"); assert.equal(ctx.headers["X-Biz-Code"], "400"); }); test("请求体超限转成 413 业务码", async () => { const ctx = createCtx(); const err = new Error("request entity too large"); err.status = 413; await createErrorMiddleware()(ctx, async () => { throw err; }); assert.equal(ctx.body.code, 413); assert.equal(ctx.body.msg, "请求体过大"); }); test("未预期异常收敛为 500,且不把内部信息回传客户端", async () => { const ctx = createCtx(); const err = new Error("mongodb://user:pass@host/db connect failed"); await createErrorMiddleware()(ctx, async () => { throw err; }); assert.equal(ctx.body.code, 500); assert.equal(ctx.body.msg, "服务器繁忙,请稍后重试"); assert.equal(ctx.body.data, null); assert.equal(JSON.stringify(ctx.body).includes("mongodb://"), false); }); test("响应已开始发送时不再改写响应体", async () => { const ctx = createCtx(); ctx.headerSent = true; await assert.rejects( createErrorMiddleware()(ctx, async () => { throw new Error("late failure"); }), /late failure/ ); assert.equal(ctx.body, null); });