| Unfortunately error handling in Node.js is a total mess. As with most new technologies there are few standards and whatever standards there are are subject to change. It was only a short time ago that many Node.js libs were being produced with promises. The most common style I see today is this callback style: doAsyncCall(function(err, result){
if(err){ // handle err }
});
Unfortunately this is prone to error. When writing any sort of asynchronous function - that is, 'doAsyncCall' itself, you need to write it in the following way: function doAsyncCall(cb){
// .. do some async stuff
if(// error has been thrown){
callback(err);
} else {
callback(null /* this is where confusion happens */, result);
}
}
When writing such code you need to be very consistent and very aware of what error handling style is being used. It can be jarring for some to intentionally pass null as the first argument.I am personally a fan of the `if(result typeof Error)` style but it is not common. Many frequently used libraries, like Mongoose, use the (err, result) style. Because any async call can theoretically fail, and because you need to catch every potential error, it is common for starting programmers (and even experienced ones) to miss an edge case or two. I advocate using upstart or a similar scheme to make sure your Node server stays alive, even if you happen to have missed an error somewhere. |
I personally love this style even though it makes you write more boiler-plate code, it forces you to write exception-safe code from the start. Also, it forces a structure on all of your code that you can instantly recognize as missing if someone forgets to check for err in the callback.
If you can stick with the style, it's fairly difficult to write code that doesn't deal with errors gracefully.