How to get Type of Exception in Javascript
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
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