69059

How to raise custom error message in Sails.js

Question:

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: function (req, res) { var u = { firstName: req.param('firstName'), lastName: req.param('lastName'), email: req.param('email'), password: req.param('password'), }; User.create(u).done(function(err,user){ if(err) { if( err.code == 'ER_DUP_ENTRY' ) { return new Error('Duplicate: email address already in use.','UserController'); } console.log( err ); return; } console.log( user ); }); } }

So I am trying to capture the 'ER_DUP_ENTRY' error code and return a custom error message, but I am having no luck as written. How exactly should I be doing this?

Answer1:

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 <a href="https://github.com/balderdashy/sails-docs/blob/master/reference/Response.md" rel="nofollow">res object</a> 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.

Recommend

  • How create references between elements in XML
  • uniqness insertion in native xml database
  • Which JQuery document.ready is better? [duplicate]
  • How to find the start and end date of a previous month in PHP [duplicate]
  • Element wise exp() of scipy sparse matrix
  • iPhone: 5 seconds video capture
  • Printing out Japanese (Chinese) characters
  • How to share a database between ASP.NET MVC 5 application and .NET console application?
  • How to clear specified format data from clipboard?
  • ASP.NET, C# How to Pass a StringQuery to a custom SQL Command
  • Merge list of objects into consistent list based on common matching attribute in Python
  • Insert records if not exist SQL Server 2005
  • Unique Permutations - with exceptions
  • Cloud Code function running twice
  • Android application: how to use the camera and grab the image bytes?
  • Detect when Facebook like button is clicked
  • Needing to do .toArray() to get output of mongodb .find() on key name not value
  • Make VS2015 use angular-cli ng at build time in a .NET project
  • Meteor: Do Something On Email Verification Confirmation
  • Cannot resolve symbol 'MyApi'
  • NHibernate Validation Localization with S#arp Architecture
  • How to get address from latitude and longitude android google map v2 [duplicate]
  • Ajax jQuery multiple calls at the same time - long wait for answer and not able to cancel
  • Bug in WPF DataGrid
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Redux, normalised entities and lodash merge
  • Upload files with Ajax and Jquery
  • How to pass list parameters for each object using Spring MVC?
  • AngularJs get employee from factory
  • Proper way to use connect-multiparty with express.js?
  • using HTMLImports.whenReady not working in chrome
  • Hits per day in Google Big Query
  • how does django model after text[] in postgresql [duplicate]
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Linking SubReports Without LinkChild/LinkMaster
  • How can I remove ASP.NET Designer.cs files?
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • Python/Django TangoWithDjango Models and Databases
  • java string with new operator and a literal
  • Net Present Value in Excel for Grouped Recurring CF