【问题标题】:how to handle node js nested errors如何处理节点js嵌套错误
【发布时间】:2021-11-15 20:34:18
【问题描述】:

这只是我的代码的示例代码

async function thisThrows() {
    throw new Error("Thrown from thisThrows()");
}

async function run() {
    try {
        await thisThrows();
    } catch (e) {
        throw new Error(e)
    }
}


async function run1() {
    try{
        await run()
    }catch(e){
        throw new Error(e);
    }
}

run1().catch(error => {
    console.log(error);
});

下面的代码 sn-p 给了我嵌套的错误输出 即错误:错误:错误

Error: Error: Error: Thrown from thisThrows()
    at run1 (/Users/saunish/servify/sandbox/error-handling.js:18:15)

我需要输出是

Error: Thrown from thisThrows()

【问题讨论】:

    标签: node.js error-handling async-await promise try-catch


    【解决方案1】:

    这是因为您正在捕获错误,然后创建新错误并抛出新错误而不是原始错误。

    所有函数实际上都应该重新抛出原始错误,例如:

    async function run() {
        try {
            await thisThrows();
        } catch (e) {
            throw e // just rethrow the original
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-12-10
      • 1970-01-01
      • 2016-06-12
      • 2018-07-26
      • 2017-08-24
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多