TypeScript中自定义HttpException类型在throw语句中识别异常问题
自定义HttpException instanceof检测失效的原因及修复
问题背景
自定义继承自Error的HttpException类,抛出后在catch块中使用error instanceof HttpException判断时,即便抛出的确实是该类实例,判断也不生效,无法进入对应的处理分支。
根本原因
JavaScript的内置Error对象构造逻辑特殊:调用super(message)时,返回的对象并非子类的this实例,导致子类实例的原型链没有正确关联到HttpException.prototype,最终instanceof基于原型链的检测逻辑失效。
修复代码
在HttpException的构造函数中手动修正原型链即可解决问题:
class HttpException extends Error { public status?: number; public message: string; public data: any; constructor(status: number, message: string) { super(message); // 手动设置原型,修正instanceof检测的原型链问题 Object.setPrototypeOf(this, HttpException.prototype); this.status = status; this.message = message; this.data = null; this.name = 'HttpException'; } }
额外优化建议
- 捕获异常时无需重新创建
HttpException实例,直接传递原异常即可,避免丢失原异常的潜在属性:catch (error: any) { if (error instanceof HttpException) { next(error); // 直接传递原异常 } else { next(new HttpException(StatusCode.ERROR.INTERNAL_SERVER_ERROR.code, StatusCode.ERROR.INTERNAL_SERVER_ERROR.message)); } } - 不建议使用
this.__proto__ = HttpException.prototype,Object.setPrototypeOf是标准的原型设置API,兼容性更好。
内容的提问来源于stack exchange,提问作者Roni Jack Vituli
相关产品推荐
相关产品推荐

