如何在beforeCreate中处理错误?

时间:2015-04-08 13:11:35

标签: node.js sails.js waterline

我正在尝试验证是否存在外键。如果外键有效,我只想创建一个对象。

我正在查询beforeCreate中的对象,但是当我使用错误消息调用回调时,错误未得到处理(回溯)并返回500.

我想优雅地处理错误并返回400(错误请求)状态代码。

  beforeCreate: function(values, next) {
    // Verify that the brand id is valid
    Brand.findOne(values.brand, function(err, brand){
      if (err || !brand){
        return next({"error": "Brand does not exist."});
      }
      return next();
    });
  }

3 个答案:

答案 0 :(得分:1)

我不确定如果你这样做会发生什么:

return next(new Error("Brand does not exist."));

答案 1 :(得分:0)

我这样解决了:

创建Sails服务ModelError.js

module.exports = function(message, code) {
    var err = new Error();
    err.name = 'Validation';
    err.code = (code ? code : 400);
    err.invalidAttributes = {};
    err.message = message;

    return err;
};

在模型beforeCreate

beforeCreate: function(record, cb) {
  if (found) return cb(ModelError('message error!!!!!!!!', 400));
  return cb();
}

订阅response / negotiate.js

module.exports = function negotiate(data) {
  // Get access to `req`, `res`, & `sails`
  var req = this.req;
  var res = this.res;
  var sails = req._sails;

  // Set status code
  res.status((data.code ? data.code : 400));

  // Log error to console
  if (data !== undefined) {
    sails.log.verbose('Sending negotiate response: \n',data);
  }
  else sails.log.verbose('Sending negotiate response');
  // console.log(data.Errors)
  if(data.Errors) return res.jsonx({errors: data.Errors});
  if(data.message) return res.jsonx(data.message)
  return res.jsonx(data)
};

sails自动调用的任何错误都会在negotiate.js中出现,所以只需处理相同内容即可根据data.code返回错误代码。

答案 2 :(得分:0)

我知道这是一篇迟到的帖子。

这是我的解决方案

ModelError.js

module.exports = function(message, code) {
let err = new Error();
err.name = 'Validation';
err.code = {
    code: code,
    message: message
}
err.invalidAttributes = {};
err.message = message;

return err;
}

Model.js

beforeCreate: function (values, next) {
    Model.find(values.id)
        .then(function(result) {
            if (typeof result !== 'undefined') {
                next();
            } else {
                next(ModelError('Not Found', 404));
            }
        }).catch(function(err) {
            next(ModelError(err, 500));
        });
}

ExampleController.js

create: (req, res) {
    Model.create(req.body, function(err, response) {
        if (err) {
            // I have my own custom response file
            return Response.json(err.code.code, res, err.message);
        } else {
            return Response.json(201, res, 'Created', response);
        }
    })
}