难以识别 TypeScript throw 语句中的自定义异常类型

问题描述 投票:0回答:1

我在使用 TypeScript 中的自定义 HttpException 类时遇到了问题。这是类的结构:

class HttpException extends Error {
    public status: number | undefined;
    public message: string;
    public data: any; 

    constructor(status: number, message: string) {
        super(message);
        this.status = status;
        this.message = message;
        this.data = null;
        this.name = 'HttpException'; 
    }
}
 

我在某种条件下在方法中抛出此异常:

// Inside a method
if (totalBoxCount - labelCount < 0) {
    throw new HttpException(StatusCode.ERROR.BAD_REQUEST.code, `Overloaded with labels. We loaded ${labelCount - totalBoxCount} more than expected.`);
}

现在,当我在异步方法中捕获此异常时:

private someMethod = async (req: Request, res: Response, next: NextFunction) => {
    const data = req.body;
    try {
        const [result, num] = this.service.anotherMethod(data.text);
    } catch (error: any) {
        if (error instanceof HttpException) {
            next(new HttpException(error.status!, error.message));
        } else {
            next(new HttpException(StatusCode.ERROR.INTERNAL_SERVER_ERROR.code, StatusCode.ERROR.INTERNAL_SERVER_ERROR.message));
        }
    }
}

错误实例 HttpException 条件似乎没有按预期工作。即使我抛出 HttpException,if 语句内的代码块也不会执行。

我已确保 HttpException 类已正确定义并继承自 Error 类。任何关于为什么 instanceof 检查可能无法在这种情况下工作的见解将不胜感激。

感谢您的协助!

node.js typescript exception error-handling instanceof
1个回答
0
投票

扩展内置 Error 类有些棘手。这是我几个月前整理的一些对我有用的代码。我不记得我是如何得到这个的,但我确实从这里开始:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#custom_error_types

export abstract class DomainErrorBase extends Error {
    protected constructor(message: string) {
        super(message);
        this.name = this.constructor.name;
        Error.captureStackTrace(this, this.constructor);
    }
}

顺便说一句,没有必要,重新声明和重新定义(在构造函数中初始化)继承的成员可能会出现问题,例如

message

© www.soinside.com 2019 - 2024. All rights reserved.