packServer/backend/app/middleware/error_handler.js
liufumingren bd2363bf00 chore: 初始化仓库(backend / frontend / extension 三块)
- backend/:Egg 3 纯 JSON 接口服务(MySQL 8 + Redis),全部走 header 令牌鉴权;
  已彻底去掉服务端渲染(删除 page 控制器 / app/view / nunjucks / session / CSRF),
  开发时把页面请求反代到前端 dev server,生产托管 frontend/dist(SPA 回退)。
  单测 91 个通过(不需要本机数据库)。
- frontend/:Vite + Vue3 + TypeScript 的 SPA(登录 / 注册 / 找回密码 / 扫码登录与确认 /
  首页统计 / 设备管理 / 扫码记录 / 个人中心 / 测试页),vue-tsc 类型检查与构建通过。
- extension/:MV3 浏览器扩展(零构建),注入第三方 WMS 页面识别运单号并打开溯源页。
- 忽略规则统一放根 .gitignore:node_modules、dist、logs / logs-*、run、typings、
  .env*、config.local.js(含本机数据库与 Redis 密码,绝不入库)。
2026-10-17 08:50:32 +08:00

53 lines
2.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/**
* 统一错误处理(后端不再渲染页面 → 只会返回 JSON 或纯文本)
*
* - 接口请求(`/api/*`、`/health` 或声明了 Accept: application/json)→ `{ ok:false, message }`
* - 其它请求(正常都被 app/middleware/frontend.js 接走了)→ 一行纯文本
*
* 4xx 返回原始消息,5xx 只对外返回「服务器内部错误」并记入 common-error.log。
*/
module.exports = () => {
return async function errorHandler(ctx, next) {
try {
await next();
// 没匹配到任何路由的接口请求:框架/koa 默认回 HTML 404(客户端按 JSON 解析会报
// `Unexpected token '<'`),这里统一成 JSON —— 控制器自己给的 404(对象 body)不动
// ⚠️ 给 ctx.body 赋值会把「默认的 404」顶成 200,所以必须显式把状态码钉回 404
const isApiPath = ctx.path.startsWith('/api/') || ctx.path === '/health';
if (ctx.status === 404 && isApiPath && !(ctx.body && typeof ctx.body === 'object')) {
ctx.body = { ok: false, message: '接口不存在' };
ctx.status = 404;
}
} catch (err) {
const status = err.status >= 400 && err.status < 600 ? err.status : 500;
if (status >= 500) {
// 交给框架的 onerror 记录日志(common-error.log)
ctx.app.emit('error', err, ctx);
} else {
ctx.logger.warn('[http] %s %s -> %s %s', ctx.method, ctx.url, status, err.message);
}
// 响应已经开始发送(例如已反代出去 / 流式输出)时不能再改 body
if (ctx.headerSent) return;
const message = status >= 500 ? '服务器内部错误' : err.message;
// 接口请求返回 JSON,其它(理论上都被 frontend 中间件接走了)返回纯文本
const isApi = ctx.path.startsWith('/api/') || ctx.path === '/health' || ctx.acceptJSON;
ctx.status = status;
if (isApi) {
ctx.body = { ok: false, message };
return;
}
ctx.type = 'text/plain; charset=utf-8';
ctx.body = `${status} ${message}`;
}
};
};