fix: 统一错误出口并把 user 服务非 2xx 视为故障
- 新增最外层错误中间件:body-parser 的 400/413 等也转成约定 JSON, 客户端只收通用文案,5xx 详情仅进日志 - token 校验对 user 服务非 2xx 抛错而非按未登录处理, 避免服务抖动时在线用户被负缓存 60 秒踢回登录页
This commit is contained in:
@@ -27,6 +27,51 @@ const largeBodyParser = bodyParser({
|
|||||||
textLimit: LARGE_BODY_LIMIT,
|
textLimit: LARGE_BODY_LIMIT,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 客户端错误只回通用文案:body-parser / 框架的原始 message 可能带内部字段名
|
||||||
|
const CLIENT_ERROR_MESSAGES = {
|
||||||
|
400: "请求参数格式不正确",
|
||||||
|
401: "未授权",
|
||||||
|
403: "禁止访问",
|
||||||
|
404: "资源不存在",
|
||||||
|
405: "请求方法不支持",
|
||||||
|
413: "请求体过大",
|
||||||
|
415: "不支持的请求格式",
|
||||||
|
429: "操作过于频繁,请稍后再试",
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统一错误出口
|
||||||
|
*
|
||||||
|
* 业务 handler 内部已各自 catch,这里兜住中间件层的异常:
|
||||||
|
* 非法 JSON、请求体超限、静态资源异常等。所有响应仍走 body.code 约定,
|
||||||
|
* HTTP 状态保持 200,避免客户端因 413/400 直接拿到非 JSON 文本。
|
||||||
|
*
|
||||||
|
* @returns {Function} Koa 中间件
|
||||||
|
*/
|
||||||
|
export function createErrorMiddleware() {
|
||||||
|
return async (ctx, next) => {
|
||||||
|
try {
|
||||||
|
await next();
|
||||||
|
} catch (err) {
|
||||||
|
// 响应已开始发送时无法再改 body,交给 Koa 默认处理
|
||||||
|
if (ctx.headerSent) throw err;
|
||||||
|
|
||||||
|
const status = Number(err?.status || err?.statusCode) || 500;
|
||||||
|
if (status >= 400 && status < 500) {
|
||||||
|
ResponseUtil.error(
|
||||||
|
ctx,
|
||||||
|
CLIENT_ERROR_MESSAGES[status] || "请求处理失败",
|
||||||
|
null,
|
||||||
|
status
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 5xx 的详细原因只进日志,不回传堆栈/连接串等内部信息
|
||||||
|
ResponseUtil.internalError(ctx, err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
class APP {
|
class APP {
|
||||||
constructor() {
|
constructor() {
|
||||||
this.app = new Koa();
|
this.app = new Koa();
|
||||||
@@ -46,6 +91,9 @@ class APP {
|
|||||||
this.app.proxy = true;
|
this.app.proxy = true;
|
||||||
this.app.proxyIpHeader = "X-Real-IP";
|
this.app.proxyIpHeader = "X-Real-IP";
|
||||||
|
|
||||||
|
// 统一错误出口必须在最外层:body-parser 的 400/413 也要转成约定 JSON
|
||||||
|
this.app.use(createErrorMiddleware());
|
||||||
|
|
||||||
// 线上 nginx 只代理 /health 与 /user;保留 /static 供本机访问,
|
// 线上 nginx 只代理 /health 与 /user;保留 /static 供本机访问,
|
||||||
// 同时提供 /health/static,避免独立 /static 请求落到其他服务的默认响应
|
// 同时提供 /health/static,避免独立 /static 请求落到其他服务的默认响应
|
||||||
this.app.use(mount('/health/static', serve(STATIC_DIR)));
|
this.app.use(mount('/health/static', serve(STATIC_DIR)));
|
||||||
|
|||||||
@@ -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);
|
||||||
|
});
|
||||||
@@ -36,6 +36,11 @@ async function lookup(body) {
|
|||||||
body: JSON.stringify(body),
|
body: JSON.stringify(body),
|
||||||
signal: AbortSignal.timeout(LOOKUP_TIMEOUT),
|
signal: AbortSignal.timeout(LOOKUP_TIMEOUT),
|
||||||
});
|
});
|
||||||
|
// 非 2xx 视为服务故障而不是「token 无效」:曾把 5xx 当作未登录,
|
||||||
|
// 在线用户会被负缓存 60 秒,表现为莫名被踢回登录页
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`user service responded ${res.status}`);
|
||||||
|
}
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
return data?.data?.user || null;
|
return data?.data?.user || null;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user