我有以下代码引发并捕获自定义异常:
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相关的已知陷阱会导致在构建过程中丢失类层次结构?