fix: 统一错误出口并把 user 服务非 2xx 视为故障

- 新增最外层错误中间件:body-parser 的 400/413 等也转成约定 JSON,
  客户端只收通用文案,5xx 详情仅进日志
- token 校验对 user 服务非 2xx 抛错而非按未登录处理,
  避免服务抖动时在线用户被负缓存 60 秒踢回登录页
This commit is contained in:
lik
2026-11-08 11:59:31 +08:00
parent d21f5da682
commit ffa6d8c1e3
3 changed files with 127 additions and 0 deletions
+48
View File
@@ -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)));