ค้นหาเว็บไซต์

javascript - การใช้ error instanceof X ไม่ทำงานตามที่คาดหวัง


ฉันมีคลาสชื่อ UserInputError ที่สืบทอดมาจาก Error

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

เมื่อฉันพยายามจับข้อผิดพลาดเฉพาะนี้ฉันใช้

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

ผลลัพธ์คือ

false true

ทำไม instanceof ถึงไม่ทำงานตามที่คาดไว้? บริบทสำคัญหรือ? หรือเป็นเพราะฉันใช้ any?

แก้ไข :

นี่คือโค้ดสแน็ปช็อตที่ทำให้เกิดข้อผิดพลาด

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

หมายเหตุ1: ฉันไม่ได้ throw UserInputError แทนที่จะเป็น throw new UserInputError

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

หมายเหตุ2: ฉันกำลังใช้สิ่งนี้กับ NodeJs ไม่ใช่เบราว์เซอร์