res.negotiate()

Given an error (err), send an appropriate error response back down to the client. Especially handy for handling potential validation errors from Model.create() or Model.update().

Usage

  1. return res.negotiate(err);

Details

Like the other built-in custom response modules, the behavior of this method is customizable.

res.negotiate() examines the provided error (err) and determines the appropriate error-handling behavior from one of the following methods:

The determination is made based on err‘s “status” property. If a more specific diagnosis cannot be determined (e.g. err doesn’t have a “status” property, or it’s a string), Sails will default to res.serverError().

Example

  1. // Add Fido's birthday to the database:
  2. Pet.update({name: 'fido'})
  3. .set({birthday: new Date('01/01/2010')})
  4. .exec(function (err, fido) {
  5. if (err) return res.negotiate(err);
  6. return res.ok(fido);
  7. });

Notes

  • This method is terminal, meaning it is generally the last line of code your app should run for a given request (hence the advisory usage of return throughout these docs).
  • res.negotiate() (like other userland response methods) can be overridden - just define a response module (/responses/negotiate.js) and export a function definition.
  • This method is used as the default handler for uncaught errors in Sails. That means it is called automatically if an error is thrown in any request handling code, but only within the initial step of the event loop. You should always specifically handle errors that might arise in callbacks/promises from asynchronous code.