javascript - 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 相关的已知问题会导致在构建过程中丢失类层次结构?
解决方案
推荐阅读
- apache - 什么是在 Apache 中执行透明内容协商
- java - 我可以将 JLabels 添加到数组中吗?
- video-streaming - 视频流
- ruby-on-rails-5 - 如何在 ActiveAdmin 中使用日期选择器而不重写创建表单?
- c - 循环后挂在输入上的 PDCurses
- docker - Docker:OpenShift Origin 3.6 上的权限错误
- pandas - 为什么 Pandas 反转我的 x 轴顺序?
- sql - Postgresql 使用通用月份参数将查询转换为视图
- javascript - 我可以使用 SQL 查询显示 JSON 数据吗?
- r - 如何将 TSQL 参数传递给 dplyr 过滤子句?