instanceof为我的自定义异常类返回错误

时间:2020-03-05 14:58:55

标签: javascript typescript webpack

我有以下代码引发并捕获自定义异常:

class CreateValidationError extends Error {
    constructor(message?: string) {
        super(message);
        Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
        this.name = CreateValidationError.name; // stack traces display correctly now 
    }
}

function doSomething() {
    throw new CreateValidationError('abc')
}

function funcOne() {
    try {
        doSomething()
    }
    catch(e) {
        if (e instanceof Error) { console.log('its an error') }// this prints correctly 

        if (e instanceof CreateValidationError) { console.log('its a CreateValidation error') } // this does not print 
    }
}

问题在于instanceof仅检测基类,而不检测派生类。

在定义自定义异常时我做错了什么吗?

或者是否有与TypeScript或Webpack相关的已知陷阱会导致在构建过程中丢失类层次结构?

0 个答案:

没有答案