johnmalkovitch johnmalkovitch - 4 months ago 9x
Node.js Question

Handling errors at a global level

I am trying to understand how to build my error handling system for my api.

Let's say I have a the following line in a controller method :

var age =;


json = {"id":1, "name":"John", info": {"age":27, "sex":"m"}}

Let's say that the object doesn't contain an
field, I'll get the following error
TypeError: Cannot read property 'info' of undefined
and my server will crash.

Is there a way to make a higher level abstraction and catch all the potential errors that I could have? Or should I have a try/catch system for each of the methods of my controllers?



Don't use the code snippet below if you do not understand its implications, please read the whole answer.

You can use the node way for uncaught errors. Add this in your config/bootstrap.js

process.on('uncaughtException', function (err) {
    // Handle your errors here

    // global.__current__ is added via middleware
    // Be aware that this is a bad practice,
    // global.__current__ being a global, can change
    // without advice, so you might end responding with 
    // serverError() to a different request than the one
    // that originated the error if this one happened async 

Now, can doesn't mean should. It really depends on your needs, but do not try to catch BUGS in your code, try to catch at a controller level the issues that might not happen every time but are somehow expected, like a third-party service that responded with empty data, you should handle that in your controller. The uncaughtException is mainly for logging purposes, its better to let your app crash if there is a bug. Or you can do something more complicated (that might be better IMHO), which is to stop receiving requests, respond to the error 500 (or a custom one) to user that requested the faulty endpoint, and try to complete the other requests that do not relate to that controller, then log and shutdown the server. You will need several instances of sails running to avoid zero downtime, but that is material for another question. What you asked is how to get uncaught exceptions at a higher lvl than the controllers.

I suggest you read the node guide for error handling

Also read about domains, even thought its are deprecated you can use it, but you would have to deal with them per controller action, since sails does not provide any help with that.

I hope it helps.