JavaScript check if an object is an instance of type Error using check-more-types library

In this JavaScript tutorial we learn how to check whether an object is an instance of type Error or not using the error() method of check-more-types library.

Create the sample project

Firstly we create an empty project with the following command.

mkdir sample-project
cd sample-project
npm init -y

And install the check-more-types module using the following command.

npm install check-more-types --save

How to check if an object is an instance of type Error in JavaScript

To check if a given object is an instance of type Error or not we can use the error() method of check-more-types library. The method returns true if the given argument is an instance of type Error.

In the sample-project directory create a new file named check-error.js as below.

check-error.js

var check = require('check-more-types');

try {
    throw new TypeError();
} catch(ex) {
    console.log(check.error(ex));
    var sample = "test"
    console.log(check.error(sample));
}

Run the check-error.js file using the following command.

node check-error.js
The output is:
true
false

More examples of how to use the check.error() method

check-error-example.js

var check = require('check-more-types');

try {
    var testString = "test";
    throw new SyntaxError();
} catch(ex) {
    if(check.error(ex)) {
        console.log('ex is type of error.');
    } else {
        console.log('ex is not type of error.');
    }

    if(check.error(testString)) {
        console.log('testString is type of error.');
    } else {
        console.log('testString is not type of error.');
    }
}

Run the check-error-example.js file using the following command.

node check-error-example.js
The output is:
ex is type of error.
testString is not type of error.

Happy Coding 😊