Files
agent/app/server/error-handler.js
kicer b657a22fe2 fix(server): 下载响应接住 sendFile 异步错误,点文件不再 404 也不再吐堆栈
- sendDownload 加 dotfiles:'allow' 与图片分支对齐:.env / .gitignore 这类点文件
  本来存在,却被 send 的默认 ignore 策略当成不存在抛 NotFoundError
- sendDownload / sendInlineImage 都补上 sendFile 回调,失败统一走 sendFileError:
  4xx 折叠成 404、正文只留一行纯文本。此前错误没人接,落进 Express 默认处理器,
  非 production 环境下把 err.stack 拼成 HTML 吐给请求方(服务端绝对路径、源码
  文件名+行号、依赖版本),而 /p/<id> 是挂在 auth 之前的匿名可达端点
- 新增 error-handler.js 作统一错误出口,末尾挂在 server.js:任意路由漏出的异常
  同样只回一行纯文本,栈只进日志、不再进响应体
2026-11-12 07:45:06 +08:00

33 lines
1.8 KiB
JavaScript
Raw Permalink 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.
// 统一 HTTP 错误出口(Express 的四参数错误中间件,必须在所有路由之后注册)。
//
// 存在理由:Express 默认错误处理器只有 NODE_ENV=production 时才回一句干净的 500,
// 其余环境把 err.stack 拼成 HTML 吐给请求方——里面是服务端绝对路径、源码文件名+行号、
// 依赖版本。本地形态 NODE_ENV 通常未设置,等于默认开启。而 /p/<id> 这类端点匿名可达
// (见 routes/public-files.js),一次 sendFile 失败就能把整份栈打到公网。
//
// 策略:状态码照旧透出(body-parser 的 400/413、send 的 404 都靠它,客户端要能区分),
// 正文永远固定一句,栈只进日志。
'use strict';
const log = require('./log');
// 只认 err.status / err.statusCode 里的合法 4xx-5xx;其余(含没状态码的普通 Error)一律 500。
function statusOf(err) {
const s = Number(err && (err.status || err.statusCode));
return s >= 400 && s <= 599 ? s : 500;
}
function errorHandler(err, req, res, next) { // eslint-disable-line no-unused-vars
const status = statusOf(err);
const where = (req && req.method ? req.method + ' ' + (req.originalUrl || req.url || '') : '(unknown)');
// 5xx = 未预期异常,栈进日志;4xx 是调用方问题,一行 message 足够。
if (status >= 500) log.error('http', where + ' → ' + status + ':' + ((err && err.stack) || err));
else log.warn('http', where + ' → ' + status + ':' + ((err && err.message) || err));
if (res.headersSent) { if (res.destroy) res.destroy(); return; } // 响应已开始,只能断开
res.removeHeader('Content-Disposition'); // 可能已被 download-send 设过,错误体不该带文件名
res.status(status).type('text').send(status >= 500 ? 'internal error' : 'request failed');
}
module.exports = { errorHandler, statusOf };