【问题标题】:How to properly pass HTTP error code to error handling middleware?如何正确地将 HTTP 错误代码传递给错误处理中间件?
【发布时间】:2019-03-20 22:03:14
【问题描述】:

我正在使用 node.js 和 express 框架构建 RESTful API,并且我正在寻找一种构建单个错误处理中间件的方法。我目前的做法是:

router.get('/some-resource', (req, res, next) => {
  // some logic that resolves to BAD REQUEST
  const error = new Error('Bad request example message')
  error.code = 400; // should I do this?
  next(error);
});

我的错误处理中间件如下:

const env = process.env.NODE_ENV;
const ErrorHandler = (error, req, res, next) => {
  const {code, stack} = error;
  if (env === 'production')
    return res.sendStatus(code || 500);
  res.status(code).send(stack);
};

module.exports = ErrorHandler;

我应该只将 HTTP 错误代码分配给 Error 对象的实例,还是认为这是一种不好的做法?是否应该在路由级别指定响应代码?有没有更好的方法来做到这一点?

【问题讨论】:

    标签: javascript node.js rest express


    【解决方案1】:

    使用常规的 Error 对象传递代码非常好,但 code 有点过于通用,也可能被其他错误使用,所以 httpCode 可能会更好。

    但我个人更喜欢使用自定义类,这样我就不需要记住错误代码或不小心输入错误的数字,并且您可以清楚地确定它确实是代表 http 错误代码的错误,并且 @ 987654323@ 不涉及其他内容。

    所以设置可能如下所示:

     class HttpError extends Error {
        constructor(code, message) {
          super(message)
          this.code = code
        }
     }
    
    
     class BadRequestError extends HttpError {
        constructor(message) {
          super(400, message)
        }
     }
    

    错误处理中间件可能如下所示:

    const env = process.env.NODE_ENV;
    const ErrorHandler = (error, req, res, next) => {
      if( error instanceof HttpError ) {
        res.status(error.code || 500)
      } else {
        // maybe some additional internal logging that a "wrong" error object arrived here
        res.status(500)
      }
    
      if (env === 'production') {
        res.send();
      } else {
        res.send(error.stack);
      }
    };
    
    module.exports = ErrorHandler;
    

    【讨论】:

      【解决方案2】:

      你在正确的轨道上。 Error object 的 MDN 文档会有所帮助。此外,跨平台 StackTrace.js 在您的场景中非常有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-09
        相关资源
        最近更新 更多