首页 > 解决方案 > instanceof 为我的自定义异常类返回错误

问题描述

我有以下代码来抛出和捕获自定义异常:

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 相关的已知问题会导致在构建过程中丢失类层次结构?

标签: javascripttypescriptwebpack

解决方案


推荐阅读