fix: 统一错误出口并把 user 服务非 2xx 视为故障
- 新增最外层错误中间件:body-parser 的 400/413 等也转成约定 JSON, 客户端只收通用文案,5xx 详情仅进日志 - token 校验对 user 服务非 2xx 抛错而非按未登录处理, 避免服务抖动时在线用户被负缓存 60 秒踢回登录页
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
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);
|
||||
});
|
||||
Reference in New Issue
Block a user