处理Sails.js中的异常

时间:2015-01-23 18:40:04

标签: javascript exception exception-handling sails.js

我正在使用 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响应以处理此类异常是否是最佳方法?或者创建一些自定义中间件是否更好?如果是这样,你能提供一个简单的例子吗?

1 个答案:

答案 0 :(得分:2)

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

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

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."
    }
}