Last updated: Mar 2, 2024
Reading timeยท3 min
Use the instanceof
operator to check if a variable is of type Error
, e.g.
err instanceof Error
.
The instanceof
operator will return true
if the variable stores an
instance of the Error
class.
const err = new Error('๐ฃ๏ธ Something went wrong'); console.log(err instanceof Error); // ๐๏ธ true
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.
const err = new Error('๐ฃ๏ธ Something went wrong'); class Person {} console.log(err instanceof Error); // ๐๏ธ true console.log(err instanceof Person); // ๐๏ธ false if (err instanceof Error) { console.log('The variable is of type error'); } else { console.log('The variable is NOT of type error'); }
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
We created a NotFoundError
class that extends from the Error
class.
Using the instanceof
operator returns true
for both the Error
and
NotFoundError
classes.
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 that we're basically saying:
An error has
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 argument 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 sample, 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.
You can learn more about the related topics by checking out the following tutorials: