Node (or Javascript really) can throw errors in exceptions using the throw keyword:
if (something_went_wrong) { throw new Error('Doh!'); }
You can also add additional parameters to the Error object by default to give more semantic meaning to your errors in your program. With this in mind, you will not want to throw an error in your route handler, because this will cause the process and your server to crash.
When using route handlers in Sails (or really really), you should certainly check the type of error and respond to the client accordingly.
// -- Route handler app.get('/something', function (req, res, next) { DB.create({ username: 'user' }, function (err, docs) { if (err) { // This checks to see if we have a unique error from MongoDB // and send the appropriate response to the client if (err.code === 11000 || error.code === 11001) { return res.send(409); // or return res.json(409, {message: "User exists"}); } // Any other error type is assumed to be an internal error so we pass it // down the chain to the error handler middleware return next(err); } // This is a client error, not an internal error so we respond to the client // with the appropriate client error type if (docs.length === 0) return res.send(404); if (user.notAuthorized) return res.send(403); res.send('All Good'); }); });
Please note that in the case when the database responds with an internal error, we move on to the next() function, which is picked up by intermediate error-handling software in a chain. Any middleware with arrival 4 is defined as middleware for error handling. Sails probably have some default error handler, but you can probably also override it - you will need to check the relevant documents for this information, since I prefer which control I get using only Express.
source share