Sails.js自定义错误类型?

时间:2016-01-25 01:29:54

标签: sails.js

我目前正在构建一个Sails.js应用。我在我的控制器中使用promises。我想定义一组自定义错误对象,以简化错误传播。您在哪里定义自定义错误对象,以便它们可以在控制器和服务文件之间访问?

例如:

CustomErrors.js:(定义自定义错误的最佳位置在哪里?)

function ErrorNotFound(message) {
  this.name = 'Error Not Found';
  this.message = message || 'Not Found';
    this.status = 404;
  this.stack = (new Error()).stack;
}
ErrorNotFound.prototype = Object.create(Error.prototype);
ErrorNotFound.prototype.constructor = ErrorNotFound;

Controller1.js:

Model.find({attr1: 123, name: 'Joe Blogs}).then(function(model){
  if(!model) throw new ErrorNotFound("The specified model was not found");
  else return Model2.find({uuid: req.uuid, colour: model.favourite_colour});
})then(function(model2){
  return res.json(model2);
}).catch(function(err){
  //if ErrorNotFound is caught, it will return Not Found 404
  //otherwise it will return ServerError 500
  res.negotiate(err); 
})

0 个答案:

没有答案