ExpressJs 在生产模式下发送堆栈

ExpressJs sends stack in production mode

我正在尝试在上线前模拟生产,我有以下设置

package.json

"start": "cross-env NODE_ENV=production node dist/index.js",

index.ts

console.log(process.env.NODE_ENV) // prints "production"
router.use(handleError);

错误-handler.ts

import { serializeError } from 'serialize-error';

export function handleError(
  err: ResponseError,
  _req: Request,
  resp: Response,
  _next: NextFunction
): void {
  if (err) {
    resp.status(err.statusCode || 500).json(serializeError(err));
  }
}

使用此设置,当出现错误请求时,我会在响应中获得堆栈,这是我不想要的。

如果我添加到错误处理函数

  if (err) {
     if (process.env.NODE_ENV === 'production') { 
          delete err.stack;
          resp.status(err.statusCode || 500).json(serializeError(err));
     }
  }

然后我没有得到堆栈。但是 Express 不是应该在生产中自动删除堆栈吗?

Express 在这里没有机会,因为您正在序列化错误 object 自己并发送它。所以,你已经从 Express 手中接过了这份工作。堆栈仍将处于错误 object 本身。这来自错误的来源。

如果你想在 non-production 模式下发送错误堆栈,我建议你这样修改你的提议:

if (err) {
     if (process.env.NODE_ENV === 'production') { 
          delete err.stack;
     }
     resp.status(err.statusCode || 500).json(serializeError(err));
}

不过,我从未将堆栈跟踪作为响应的一部分发送。相反,我总是在本地记录错误:

if (err) {
     console.log(err);
     delete err.stack;
     resp.status(err.statusCode || 500).json(serializeError(err));
}

Is there anything in Express default functionalities besides this stack that my serializeError prevents me from benefiting from?

值得一读Express doc page on error handling。如果 headers 已被发送(例如您在流式传输响应时遇到错误),它们的默认处理程序会尝试不同的行为,因为此时您的选择受到更多限制。

他们还强制任何 err.statusCode 不是 4xx 或 5xx 到 500,因为他们想确保它被报告为错误状态代码。您正在允许错误 object 上的任何内容通过。