error instanceof X doesn't work as expected

Viewed 135

I have a class called UserInputError that extends Error

export default class UserInputError extends Error {
    constructor(message: string) {
        super(message);
        this.name = "UserInputError";
    }
}

When i try to catch this specific error i use

try {
     // some code
} catch(e: any) {
    // catch logic here
    console.log(e instanceof UserInputError, e.name === "UserInputError");

The output is

false true

why instanceof doesn't work as expected? does context matter? or was it because I've used any?

Edit:

This is the code snippet that throws the error

if (invalidNumberOfMethods) {
    throw new UserInputError("you must chose one method");
}

NOTE1: I don't throw UserInputError instead of throw new UserInputError

> grep -R --include "*.ts" --exclude-dir=node_modules "throw UserInputError" .
> echo $?
> 1

NOTE2: I'm using this with NodeJs, not the browser.

0 Answers
Related