Search code examples
node.jserror-handlingnullundefinedcode-readability

Checking error parameters in node


It is a convention in node to pass an error parameter to asynchronous operations:

async.someMagicalDust(function(callback) {
     // some asynchronous task

     // […]
     callback();

}, function(err) {
     // final callback

    if(err) throw err;    
    // […]

});

Maybe I'm too naive, but I've never been a big fan of the if(variable) notation — probably inherited from C, for reasons that have already been discussed many times in the past.

On the other hand, I have sometimes encountered a null parameter and this error check:

if(typeof err !== 'undefined' && err !== null)

is a bit too verbose.

Another solution would be

if(err != null)

but I think the non-strict check can be tricky, even though I consider it normal when comparing with null.

What's the best way to check error parameters in node?


Solution

  • Use if(err).

    It is designed to be used in this fashion. Node-style callbacks are supposed to set the error to a non-falsy value only in case of actual error. You won't find any sane example of setting err to '' or 0 to signify error.

    Just like YlinaGreed has noted, if module conventions cnahge from null to undefined to 0 to maybe even NaN, you are still safe. I've never been hit by this having only used if(err).

    On the other hand, you may want to use coffescript, which would translate for you

    unless err? then...
    

    into

    if (typeof err === "undefined" || err === null) {
    

    mimicking the most common pattern.

    Some links to corroborate the if(err) approach:

    The convention seems to be passing an error object as the first argument and null for no error so even if you pass an empty object, it's still an error.

    If you use the popular express framework, you should have used the next callback to return from middleware, which follows the errback convention.

    I believe that most people prefer more concise next() than next(null), which means that the first argument will evaluate to undefined rather than null, and this is certainly perfectly normal usage.