Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control the error code that sails.js sends from within a Model lifecycle method?

I am writing a lifecycle method on a model that checks to see if a user exists before saving the new record. If the user does not exist, I want the server to respond with a 400 Bad Request code. By default, sails.js seeems always to send back 500. How can I get it to send the code that I want?

Here is my current attempt:

beforeCreate: function(comment, next) {

  utils.userExists(comment.user).then(function(userExists) {

    if (userExists === false) {
      var err = new Error('Failed to locate the user when creating a new comment.');
      err.status = 400; // Bad Request
      return next(err);
    }

    return next();

  });

},

This code, however, does not work. The server always sends 500 when the user does not exist. Any ideas?

like image 803
fraxture Avatar asked Feb 20 '26 07:02

fraxture


1 Answers

you don't want to do that in a lifecycle callback. Instead, when you're going to make the update, you can do a check of the model and you have access to the res object...for example:

User.find({name: theName}).exec(function(err, foundUser) {
  if (err) return res.negotiate(err);

  if (!foundUser) {
    return res.badRequest('Failed to locate the user when creating a new comment.');
  }

  // respond with the success
});

This might also be moved into a policy.

like image 84
JohnGalt Avatar answered Feb 23 '26 08:02

JohnGalt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!