无法判断抛出的错误是否为自定义错误类的实例
自定义Http错误类的instanceof检测问题
我创建了一个继承内置Error类的自定义错误类CustomHttpError,并为其添加了新属性,该错误本身可正常工作。我希望在捕获错误时对其进行显式处理。
自定义错误类代码
export default class CustomHttpError extends Error { constructor(readonly httpCode: number, readonly message: string) { super(message); this.name = 'CustomHttpError'; } }
测试代码
const CustomHttpError = require('./lib/src/errors/CustomHttpError'); try { throw new CustomHttpError(420, 'Enhance Your Calm'); } catch (e) { if (e instanceof CustomHttpError) { console.log(CustomHttpError.httpCode); } }
报错信息
if (e instanceof CustomHttpError) { ^ TypeError: Right-hand side of 'instanceof' is not callable
问题原因
自定义类用ES模块的export default导出,但测试代码用CommonJS的require导入,直接require默认导出的模块会得到一个包含default属性的对象,而非类本身,导致CustomHttpError是普通对象、不是可调用的构造函数,所以instanceof检测失败。
解决方法
方法1:调整require的导入方式
获取模块的default属性,拿到真正的类:
const { default: CustomHttpError } = require('./lib/src/errors/CustomHttpError');
方法2:改用ES模块语法导入
在项目的package.json中添加"type": "module",然后用import导入:
import CustomHttpError from './lib/src/errors/CustomHttpError';
额外修正
测试代码里还有一处错误:你访问的是类的静态属性CustomHttpError.httpCode,但httpCode是实例属性,应该改为访问捕获到的错误实例的属性:
console.log(e.httpCode);
内容的提问来源于stack exchange,提问作者Tomas Mačiulis
相关产品推荐
相关产品推荐

