Skip to content Skip to sidebar Skip to footer

How To Raise Custom Error Message In Sails.js

I am very new to Sails.js (0.9.13) and to node style programming in general. Any help appreciated. The collowing example is from a UserController: module.exports = { save: fu

Solution 1:

If what you're intending is to return an error to the client, there are several ways to go, but all of them start with the res object that is passed as an argument to your controller action. All of the latest builds of Sails have a few basic error responses baked into that object, so you can do (for example):

res.serverError(err)

instead of return new Error to show a general error page with a 500 status code. For JSON-only API calls that don't expect HTML, it'll send a simple object with the status code and the error. There's also:

res.notFound() // 404 response
res.forbidden() // 403 response
res.badRequest() // 400 response

For your "duplicate entry" error, you'll probably want something more customized. Since your example is coming from a form post, the best practice would be to actually save the error as a flash message and redirect back to the form page, for example:

req.flash('error', 'Duplicate email address');
return res.redirect('/theView');

and then in your form view, display errors using something like:

<% if (req.session.flash && req.session.flash.error) { %><%=req.flash('error')%><% } %>

As an alternative, you could just display a custom error view from your controller:

return res.view('duplicateEmail');

If you're responding to an API call, you'll want to send a status code and (probably) a JSON object:

return res.json(409, {error: 'Email address in use'});

The point is, rather than returning (or throwing) an Error object in your controller code, you want to use the res object to respond to the request in some way.


Post a Comment for "How To Raise Custom Error Message In Sails.js"