node.jsfunctionerror-handlingfunction-calls

Calling an error-first function Node JS


new to Node and having fun, however, I am encountering an issue trying to pass data to a function that has two arguments err/argTime. ex:function(err, argTime).

This works for me:

queryTrigger(moment()); //the call
//more code...

function queryTrigger(argTime) { 
            console.log(argTime);
         };

This does not work:

queryTrigger(moment()); //the call
//more code...

function queryTrigger(err, argTime) { 
        if(err) {
            throw err;
        } else {
        console.log(argTime);
        };
};

Any insight is much appreciated!


Solution

  • You need to pass a value as the error, but in the case there isn't one you can use either null or undefined as the value (to represent no error).

    // No error:
    queryTrigger(null, moment());
    
    // Explicit error:
    queryTrigger((new Error('Error!')), moment());
    
    // Variable error from function response:
    queryTrigger(isErrored(), moment());
    

    In answer to your follow-up comment, you typically only need this pattern when calling asynchronous functions where the error is raised outside of the main event loop - if you're not doing so, you can just use try/catch to deal with errors.

    I disagree with the statement in this answer with regards to best practices; the err argument is basically always going to be the first argument and is followed by pretty much every async function in the stdlib along with most (good) packages on GitHub/npm.