From ffa6d8c1e388306fa7e8c30441d92e3a6ae1fb01 Mon Sep 17 00:00:00 2001 From: lik Date: Sun, 8 Nov 2026 11:59:31 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E7=BB=9F=E4=B8=80=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E5=87=BA=E5=8F=A3=E5=B9=B6=E6=8A=8A=20user=20=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E9=9D=9E=202xx=20=E8=A7=86=E4=B8=BA=E6=95=85=E9=9A=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增最外层错误中间件:body-parser 的 400/413 等也转成约定 JSON, 客户端只收通用文案,5xx 详情仅进日志 - token 校验对 user 服务非 2xx 抛错而非按未登录处理, 避免服务抖动时在线用户被负缓存 60 秒踢回登录页 --- app.js | 48 +++++++++++++++++++++++++++ test/app_error.test.js | 74 ++++++++++++++++++++++++++++++++++++++++++ utils/user_service.js | 5 +++ 3 files changed, 127 insertions(+) create mode 100644 test/app_error.test.js diff --git a/app.js b/app.js index 15122c8..44c60dd 100644 --- a/app.js +++ b/app.js @@ -27,6 +27,51 @@ const largeBodyParser = bodyParser({ 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 { constructor() { this.app = new Koa(); @@ -46,6 +91,9 @@ class APP { this.app.proxy = true; this.app.proxyIpHeader = "X-Real-IP"; + // 统一错误出口必须在最外层:body-parser 的 400/413 也要转成约定 JSON + this.app.use(createErrorMiddleware()); + // 线上 nginx 只代理 /health 与 /user;保留 /static 供本机访问, // 同时提供 /health/static,避免独立 /static 请求落到其他服务的默认响应 this.app.use(mount('/health/static', serve(STATIC_DIR))); diff --git a/test/app_error.test.js b/test/app_error.test.js new file mode 100644 index 0000000..b062e29 --- /dev/null +++ b/test/app_error.test.js @@ -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); +}); diff --git a/utils/user_service.js b/utils/user_service.js index 6f2cd5e..2057e0b 100644 --- a/utils/user_service.js +++ b/utils/user_service.js @@ -36,6 +36,11 @@ async function lookup(body) { body: JSON.stringify(body), 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(); return data?.data?.user || null; }