【问题标题】:NodeJs http status exception handlingNodeJs http状态异常处理
【发布时间】:2017-02-16 17:15:03
【问题描述】:

我已经创建了 nodejs + express 应用程序。现在在我的应用程序中,当异常捕获的错误发送如下

app.get('/data', (req, res) => {
      if(!req.params.token){
        return res.status(403).send('Access token not provided');
      }

      //do something here
    });

除了发送 res.status(403).send('Access token not provided'); 我可以发送类似的东西

exception.js

class Forbidden {
    constructor(message,stack = null){
        this.code = 403;
        this.message = message
        this.stack = stack;
    }
}

app.js

var httpForbidden = require('exception.js');

app.get('/data', (req, res) => {
if(!req.params.token){
    return new httpForbidden ('Access token not provided');
}

//do something here
});

还有我怎样才能在一个地方捕获所有异常?

【问题讨论】:

    标签: node.js express exception-handling


    【解决方案1】:

    你可以这样使用:

    class httpError {}
    
    class httpForbidden extends httpError {
      constructor(message, stack = null) {
        super();
        this.code = 403;
        this.message = message
        this.stack = stack;
      }
    }
    
    app.get('/', (req, res) => {
      if (!req.params.token) {
        throw new httpForbidden('Access token not provided');
      }
      ...
    });
    
    app.use((err, req, res, next) => {
      if (err instanceof httpError) {
        return res.status(err.code).send(err.message);
      }
      res.sendStatus(500);
    });
    

    这使用 Express error handling middleware,它将检查抛出的错误是否是 httpError 的实例(这将是您要创建的所有 HTTP 错误类的超类),如果是,将根据代码和消息生成特定响应(否则生成通用 500 错误响应)。

    【讨论】:

      【解决方案2】:

      我喜欢创建一个单独的函数,以及其他实用程序函数(比如在 lib.js 中),它创建一个格式正确的 JSON 响应对象,并根据HTTP 状态码。

      lib.js

      var logger = require("./loggger");
      
      module.exports.sendResponse = function (res,code,message,data) {
      
          if(code<100 || code>599) {
              throw new Error("response cannot be sent. Invalid http-code was provided.");
          }
          var responseLogger = code>=500 ? logger.error : logger.debug;
      
          var responseObject = {
              "code" : code,
              "message" : message
          };
      
          if(data) {
              responseObject.data = data;
          }
      
          responseLogger(responseObject);
      
          res.status(code).json(responseObject);
      };
      

      app.js

      var lib = require("./lib");
      
      /*
      Relevant Express server code
       */
      app.get('/data', function (req,res) {
      
          if(!req.params.token){
              return lib.sendResponse(res,403,"Access token not provided");
          }
      
          // Rest of business logic
      });
      

      注意:您可以编写自己的日志记录功能,但我强烈建议在一些标准日志记录库(如 winston)上构建它

      【讨论】:

        【解决方案3】:

        不推荐使用以下方法,因为景气已更改为@hapi/boom

        https://hapi.dev/family/boom/?v=8.0.1

        在这里您可以找到@hapi/boom 库的完整文档

        -----已弃用--------

        您可以改用 boom 库,它提供了一组用于返回 HTTP 错误的实用程序

        HTTP 4xx 错误

        Boom.badRequest([消息], [数据])

        Boom.unauthorized([message],[scheme],[attributes])

        HTTP 5xx 错误

        Boom.badImplementation([message], [data]) - (别名:内部)

        Boom.notImplemented([message], [data])

        更多api文档请访问here

        【讨论】:

          【解决方案4】:

          你可以使用:

          res.code(403).json({message: '...', stack: '...'});
          

          然后发送你想要的任何东西。但是你可以通过调用响应对象的方法来做到这一点。

          还有我怎样才能在一个地方捕获所有异常?

          非常糟糕的主意。您应该处理发生的所有错误,以便您仍然可以有一些上下文以合理的方式处理它们。否则你只能抛出异常并返回 500 个错误。

          【讨论】:

          • "res.code(403).json({message: '...', stack: '...'});"这就是我现在正在做的事情。而不是我想发送“新的httpForbidden('未提供访问令牌');”
          猜你喜欢
          • 1970-01-01
          • 2020-02-10
          • 2014-04-22
          • 2017-11-24
          • 1970-01-01
          相关资源
          最近更新 更多