在创buildnext()callback之前先启动js

我正在使用风帆JS为我的Web应用程序。 我必须改变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); }); } 

所以,问题是如果有任何错误,然后下一个方法是自动redirect到serverError与错误代码500,而我想redirect与我的自定义响应(例如:badRequest,错误代码400)。 如何做到这一点?

你正在执行beforeCreate某种validation。 但是,这不是validation的正确位置。

更好的方法是使用自定义validation规则,如http://sailsjs.org/documentation/concepts/models-and-orm/validations#?custom-validation-rules或创build一个策略来处理validation。

我喜欢使用政策:

 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 }); };