在创建next()回调之前执行js

时间:2016-10-07 07:11:04

标签: node.js sails.js

我正在为我的网络应用程序使用sails js。我必须更改beforeCreate的默认行为。首先看一下代码:

beforeCreate: function(values, next) {

    //ParamsCheck is my service and 'check' is method which will validate the
    //parameters and if any invalid parameter then error will be thrown, otherwise 
    //no error will be thrown

    ParamsCheck.check(values)
   .then(() => {
     // All Params are valid and no error
     next();
   })
   .catch((err) => {
     //Some errors in params, and error is thrown
     next(err);
   });
}

所以,问题是如果有任何错误,那么下一个方法会自动重定向到带有错误代码500的serverError,而我想用我的自定义响应重定向它(例如:badRequest,err code 400)。怎么做到这一点?

1 个答案:

答案 0 :(得分:1)

您正在beforeCreate执行某种验证。但是,这不是验证的正确位置。

更好的方法是使用此处所述的自定义验证规则http://sailsjs.org/documentation/concepts/models-and-orm/validations#?custom-validation-rules或创建处理验证的策略。

我喜欢使用政策:

module.exports = function(req, res, next) {
    var values = req.body;
    ParamsCheck.check(values).then(() => {
     return next();
   }).catch((err) => {
     return res.send(422); // entity could not be processed
   });
};