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".
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?
err instanceof Error- colecmcerrin (say) an iframe, but then pass it to the parent window for handing, you'll get(err instanceof Error) === false. That's because the iframe and its parent window have distinct, differentErrorobject prototypes. Similarly an object likeobj = {};will, when passed to a function running in a different window, yeild(obj instanceof Object)===false. (Even worst, in IE, if you keep a reference to obj after its window is destroyed or navigated, trying to call object prototype fns likeobj.hasOwnProperty()will throw errors!) - Doincatch((err)=>{if (err === ENOENT)returnsENOENT is not definederror? - oldboy