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?