如何处理Express.js中的开发人员错误?

时间:2018-10-19 08:33:02

标签: node.js express error-handling

我必须区分操作错误和程序员(开发人员)错误。具有stack属性的所有错误都标记为开发人员错误。我记录了它们并使服务器崩溃。

我的问题是,这种方法是否可以正确识别所有程序员错误(试图读取“未定义”的属性(称为没有回调的异步函数,并在期望对象或整数的地方传递了“字符串”等)

这是我的错误处理程序:

app.use((err, req, res, next) => {
  // Delegate to the default Express error handler,
  // when the headers have already been sent to the client
  if (res.headersSent) return next(err);

  // Decorate with additional properties from Boom
  // If err has no specified status code or there is a stack, it is most likely a programmer error.
  // Server must crash and restart. Default error code is set to 'Internal Server Error (500)'
  const options = err.stack || !err.statusCode
    ? { data: { stack: err.stack || 'n/a', developerError: true } }
    : {};
  if (!err.isBoom) boom.boomify(err, options);

  // Add more details
  const message = {
    ...err,
    originalUrl: req.originalUrl,
    method: req.method,
    ip: req.ip
  };

  // Log server errors only. No need to log 402, 403 etc.
  if (err.isServer) winston.error(message);

  // Crash server in case of a developer error.
  // NOTE: a Node.js process manager should be set up to immediately restart the crashed server
  // eslint-disable-next-line no-process-exit
  if (err.data && err.data.developerError) process.exit(1);

  return res.status(err.output.statusCode).json(message);
});

0 个答案:

没有答案