【问题标题】:Handling exceptions in Sails.js在 Sails.js 中处理异常
【发布时间】:2015-01-23 18:40:04
【问题描述】:

我正在使用 Sails.js 开发一个 REST API 服务器。

为了便于使用和抽象,我想在我的控制器内部抛出异常,例如:

// api/controllers/TempController.js

module.exports = {
  index: function(request, response) {

    throw new NotFoundException('Specific user is not found.');

    throw new AccessDeniedException('You have no permissions to access this resource.');

    throw new SomeOtherException('Something went wrong.');

  }
};

如何自动(在全局级别)捕获这些异常并将它们转换为有效的 JSON 响应?例如:

{
  "success": false,
  "exception": {
    "type": "NotFoundException",
    "message": "Specific user is not found."
  }
}

使用内置serverError 响应来处理此类异常是否是最好的方法?还是创建一些自定义中间件更好?如果是这样,你能提供一个简单的例子吗?

【问题讨论】:

    标签: javascript exception exception-handling sails.js


    【解决方案1】:

    未处理的异常作为第一个参数data 传递给api/responses/serverError.js 中的默认响应。

    以下是如何处理此类异常的示例:

    var Exception = require('../exceptions/Exception.js');
    
    module.exports = function serverError (data, options) {
    
      var request = this.req;
      var response = this.res;
      var sails = request._sails;
    
      // Logging error to the console.
      if (data !== undefined) {
        sails.log.error('Sending 500 ("Server Error") response: \n', String(data));
      }  else {
        sails.log.error('Sending empty 500 ("Server Error") response');
      }
    
      response.status(500);
    
      if (data instanceof Exception) {
        return response.json({
          success: false,
          exception: {
            type: data.constructor.name,
            message: data.message
          }
        });
      } else {
        return response.json(data);
      }
    };
    

    当控制器抛出异常时:

    // api/controllers/TempController.js
    
    var NotFoundException = require('../exceptions/NotFoundException.js');
    
    module.exports = {
      index: function(request, response) {
    
        throw new NotFoundException('Specific user is not found.');   
    
      }
    };
    

    这将输出以下 JSON:

    {
        "success": false,
        "exception": {
            "type": "NotFoundException",
            "message": "Specific user is not found."
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      • 2018-06-14
      • 2015-11-17
      • 2018-11-16
      • 1970-01-01
      • 2017-11-09
      相关资源
      最近更新 更多