1
votes

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?

1
How you are sending the response after getting this error, can you show the code where final callback called? - abdulbarik
Actually in sails, if any parameter is passed to the next() callback of beforeCreate method, then it will be error and we will get 500 error. 'next()' is the final callback. I want to change the default response. - Devendra Verma
Whenever you pass error will callback, it gives you 500 statusCode.For bad request mean statusCode:400 you need to pass when you are responding to client - abdulbarik

1 Answers

1
votes

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