Reputation: 5510
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?
Upvotes: 3
Views: 179
Reputation: 3993
You are trying to attach an http response code to an error related to a model. Your model does not know anything about what an http response is (and it should never know).
You could handle this error in the controller to set the appropriate http code in the response.
Upvotes: 3
Reputation: 2881
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.
Upvotes: 3