jpgc
jpgc

Reputation: 764

How to use an error-handler callback in a Sails.js policy?

After asking this question, I've found that I can add a callback array to an endpoint in a sails app like this:

file: /api/policies/somepolicy.js

module.exports = thisIsAnArrayOfCallbacks;

This works ok while each member of thisIsAnArrayOfCallbacks is a function which accepts req, res, and next as arguments. The controller call executes all the functions in the array and the expected result is obtained in a normal flow.

But when using an errorHandler callback (like the one in this example) which takes an additional err parameter, it doesn't work as expected: the express-only version app.get('/path', thisIsAnArrayOfCallbacks) allows the errorHandler to fetch the exception and report a proper response to the client, but when using the sails way, the errorHandler function isn't called and the exception is thrown in the response.

How could I fetch the err parameter or catch the exception occurred in one of the functions of thisIsAnArrayOfCallbacks to send a proper response (a custom one is preferred) to the client?

Thanks in advance.

Upvotes: 4

Views: 1380

Answers (1)

sgress454
sgress454

Reputation: 24948

You're correct in that policies can't be defined as error callbacks; they're solely route-handling middleware and are actually bound to each individual route that they are applied to. Ideally, you'd catch any errors within the policy functions themselves using try/catch and send a response using something like res.forbidden(), res.badRequest(), res.serverError(), etc. In Sails v0.10 you can make any custom response you want and store it in the api/responses folder.

If you really want to implement a catch-all error handler in Sails you have two choices: either override the default 500 handler (in Sails v0.10 this is in /api/responses/serverError, in v0.9.x it's config/500.js), or (in v0.10) create custom Express middleware and load it using sails.config.express.loadMiddleware. See this SO question for details on the second option, and remember to add your custom error handler after the router and before (or in place of) the 500 handler.

Upvotes: 4

Related Questions