'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; // 5xx 默认不外传细节;显式标了 `expose` 的(例如「微信支付:签名错误」这类 // 需要运维照着改配置的)才把原始消息透出去 const message = status >= 500 && !err.expose ? '服务器内部错误' : 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}`; } }; };