javascript - 处理 Sails.js 中的异常

标签 javascript exception sails.js

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

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

// 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 响应来处理此类异常是最好的方法吗?或者创建一些自定义中间件更好?如果是的话,您能提供一个简单的例子吗?

最佳答案

未处理的异常将作为第一个参数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);
  }
};

当 Controller 抛出异常时:

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

关于javascript - 处理 Sails.js 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28116561/

相关文章:

java - 如何在tomcat的catalina.out中使用Spring MVC获取错误消息

javascript - 如何让 toJSON 在返回 Sails.js 中的对象之前等待查找?

javascript - Jquery 允许光标在 document.ready 函数之前进行

javascript - 打破 Mongoose 中的 Bluebird promise 链

javascript - 跨多个页面使用一个元素

c# - 如何通过 jQuery 调整 iFrame 的大小?

c# - 在 .net 中处理数据库异常

c# - 创建子项异常

Sais.js 更多数据库连接

javascript - 连接 API 的 SailsJS 方式。最好的方法是什么?