【问题标题】:Appending new information and rethrowing errors in nested functions在嵌套函数中添加新信息并重新抛出错误
【发布时间】:2021-12-03 16:18:21
【问题描述】:

我正在尝试实现错误处理,当函数引发错误时,调用函数应捕获该错误并向其添加一些信息,以使问题更易于理解。在下面的例子中,我试图解释我的疑惑。 firstsecond 函数由third 调用,它们各自产生不同的错误,具有不同的信息。我希望third 函数能够捕获这些错误并将一些信息附加到它们(示例当前实现的方式我丢失了firstsecond 附加到错误的信息)。

class FirstError extends Error {
    constructor(msg, num) {
        super(msg);
        this.num = num;
    }
}

class SecondError extends Error {
    constructor(msg, str) {
        super(msg);
        this.str = str;
    }
}

class ThirdError extends Error {
    constructor(msg, arg) {
        super(msg);
        this.arg = arg;
    }
}

function first(num) {
    throw new FirstError('First error', num);
}

function second(num) {
    throw new SecondError('Second error', num.toString());
}

function third(fn) {
    try {
        fn(25);
    } catch (error) {
        throw new ThirdError('Third error', fn);
    }
}

try {
    third(first);
    third(second);
} catch (error) {
    console.log(error);
    console.log(error instanceof Error);
    console.log(error instanceof FirstError);
    console.log(error instanceof SecondError);
    console.log(error instanceof ThirdError);
    console.log(error.message);
    console.log(error.stack);
}

我也知道我可以测试在third 上收到的错误实例,如下例所示。但是,由于我将有几个函数返回错误,因此这种方法将无趣,因为我会留下太多测试,并且必须在添加每种新类型的错误时更新第三个函数。

function third(fn) {
    try {
        fn(25);
    } catch (error) {
        if (error instanceof FirstError) {
            throw new ThirdError('Third error', fn);
        } else if (error instanceof SecondError) {
            throw new ThirdError('Third error', fn);
        }
    }
}

任何想法如何解决这个问题?

【问题讨论】:

    标签: javascript typescript error-handling try-catch


    【解决方案1】:

    您可以将原始错误传递给 ThirdError。然后您可以访问该错误,例如

    ...
    class ThirdError extends Error {
        constructor(msg, ...args) {
            super(msg);
            this.arg = args[0];
            this.innerError = args.slice(1);
        }
    }
    
    ...
    function third(fn) {
        try {
            fn(25);
        } catch (error) {
            throw new ThirdError('Third error', fn, error);
        }
    }
    

    输出:

    ThirdError: Third error
      ...,
      innerError: [
        FirstError: First error
            ... {
          num: 25
        }
      ]
    }
    ...
    

    【讨论】:

      猜你喜欢
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 2022-11-23
      相关资源
      最近更新 更多