Devendra Verma
Devendra Verma

Reputation: 1015

Sails js beforeCreate next() callback

I am using sails js for my web application. I have to change the default behaviour of beforeCreate. First look at the code:

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

So, the problem is if there is any error, then next method is automatically redirecting to serverError with error code 500, while I want to redirect it with my custom response(eg : badRequest , err code 400). How to achieve this?

Upvotes: 1

Views: 2000

Answers (1)

DarkLeafyGreen
DarkLeafyGreen

Reputation: 70466

You are performing some kind of validation in beforeCreate. However this is not the correct place for validation.

A better approach is to use custom validation rules as described here http://sailsjs.org/documentation/concepts/models-and-orm/validations#?custom-validation-rules or create a policy to handle the validation.

I like to use policies:

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

Upvotes: 1

Related Questions