Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Leon Biss
To check if a variable is of type Error
, use the instanceof
operator -
err instanceof Error
. The instanceof
operator returns true
if the
prototype
property of a constructor appears in the prototype chain of the
object.
const err = new Error('💣️ Something went wrong'); console.log(err instanceof Error); // 👉️ true
In this example we used the Error constructor to create a new error object.
We then used the
instanceof
operator to check if the err
variable has the prototype property of the
Error
constructor in its prototype chain.
Note that this approach would also work if you create custom errors and extend
the Error
constructor.
class NotFoundError extends Error { constructor(message) { super(message); this.name = 'NotFoundError'; this.status = 404; } } const err = new NotFoundError('product not found'); console.log(err instanceof Error); // 👉️ true console.log(err instanceof NotFoundError); // 👉️ true
In this example we create a NotFoundError
class and extend the Error
constructor.
Using the instanceof
operator returns true
for both the Error
and
NotFoundError
constructors.
IFrame
(inline frame) in your application, the instanceof
check might fail, if you do it in a parent window.As an alternative, you can use duck-typing.
function isError(error) { if (error && error.stack && error.message) { return true; } return false; } const err = new Error('💣️ Something went wrong'); console.log(isError(err)); // 👉️ true console.log(isError('test')); // 👉️ false console.log(isError({})); // 👉️ false
A simple way to think about duck-typing is, we're basically saying:
An error has a
stack
andmessage
properties. If the value also has astack
andmessage
properties, then it must be an error.
This approach works when using IFrames because we check if the parameter we passed to the function has the properties an error would have.
Where this might go wrong is if we have an object, that is not an error, but
also has the stack
and message
properties.
function isError(error) { if (error && error.stack && error.message) { return true; } return false; } // 👇️️ true console.log(isError({stack: 1, message: 'test'}));
In the code snippet, even though the object we passed to the isError
function
is not an error, it satisfies both conditions, so the function returns true
and gives us a false positive.