javascriptnode.js

checking for typeof error in JS


In JS it doesn't seem possible to check if an argument passed to a function is actually of the type 'error' or an instance of Error.

For example, this is not valid:

typeof err === 'error'

since there are only 6 possible types (in the form of strings):

The typeof operator returns type information as a string. There are six possible values that typeof returns:

"number", "string", "boolean", "object", "function" and "undefined".

MSDN

But what if I have a simple use case like this:

function errorHandler(err) {

    if (typeof err === 'error') {
        throw err;
    }
    else {
        console.error('Unexpectedly, no error was passed to error handler. But here is the message:',err);
    }
}

so what is the best way to determine if an argument is an instance of Error?

is the instanceof operator of any help?


Solution

  • You can use the instanceof operator (but see caveat below!).

    var myError = new Error('foo');
    myError instanceof Error // true
    var myString = "Whatever";
    myString instanceof Error // false
    

    The above won't work if the error was thrown in a different window/frame/iframe than where the check is happening. In that case, the instanceof Error check will return false, even for an Error object. In that case, the easiest approach is duck-typing.

    if (myError && myError.stack && myError.message) {
      // it's an error, probably
    }
    

    However, duck-typing may produce false positives if you have non-error objects that contain stack and message properties.