Check if a Variable is of type Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Leon Biss

Check if a Variable is of type Error #

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.

index.js
const err = new Error('๐Ÿ’ฃ๏ธ boom'); 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.

index.js
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.

However, if you throw an error in an 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.

index.js
function isError(error) { if (error && error.stack && error.message) { return true; } return false; } const err = new Error('๐Ÿ’ฃ๏ธ boom'); 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 and message properties. If the value also has a stack and message 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.

index.js
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.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee