简体   繁体   中英

What does 'if (err)' tests precisely in Javascript?

Many callback functions start by checking an err parameter as following:

function myCallback(err, result) {

    if ( err ) {

        // Handle error
        ...

    }

    ...

}

What does the if (err) test verifies? Does it check whether the object is null ? Does it check whether it is undefined ? Shouldn't one test for instanceof Error ? When does this test return true ?

In Node.js world, the callback functions have the following signature

function(error, result){}

If there is no error, then the error parameter is conventionally set to null , otherwise the corresponding error object.

So, the check if (err) checks if we really have an error situation or not. If the err object is null , then the check will fail (since null is falsy) otherwise the error handling code is executed.

Shouldn't one test for instanceof Error?

It is not necessarily an instance of Error object. We can even pass an object literal as an error object or even an array representing array of errors.

Does it check whether the object is null? Does it check whether it is undefined?

The test will evaluate to be falsy is the error object is either null or undefined .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM