在try-catch块内的Promise.all – 错误未被捕获

huangapple go评论84阅读模式
英文:

Promise.all inside try-catch block - error not caught

问题

我在SoF上看到一些类似的帖子,但它们似乎不是完全相同的东西。
我对JavaScript还不太熟悉,所以可能漏掉了一些明显的东西。

以下是翻译好的代码部分:

在第一个示例中,catch 子句按照我期望的方式运行,也就是说它真正捕获了funcThatThrowsError 中抛出的错误。

然而,在第二个示例中,catch 子句未捕获错误。为什么会这样呢?

请注意,如果将上面的示例更改为以下方式:

那么这个catch 子句确实捕获了错误。

我的问题是:

  1. 为什么会发生这种情况?
  2. 这是否意味着当使用 Promise.all 时,我必须为传递给 Promise.all 的每个 promise 定义一个 .catch(...) 函数,否则如果任何 promise 抛出异常,它将不会被任何地方捕获,并可能导致应用程序崩溃?

谢谢。

英文:

I saw some similar thread on SoF, but they didn't seem to be the exact same thing.
I'm new to javascript, so I might be missing something obvious.

The following code:

async function funcThatThrowsError() {
    throw new Error('some error');
}

(async () => {
    try {
        await funcThatThrowsError();
    } catch (error) {
        console.log('error caught');
    }
}

Works as I expect, meaning the catch clause is really catching the error thrown inside the funcThatThrowsError.

However, in this code:

async function funcThatThrowsError() {
    throw new Error('some error');
}

(async () => {
    try {
        Promise.all([funcThatThrowsError()]);
    } catch (error) {
        console.log('error caught');
    }
}

The catch clause doesn't catch the error. Why is that?

Note that if change the above example to be:

async function funcThatThrowsError() {
    throw new Error('some error');
}

(async () => {
    Promise.all([
        funcThatThrowsError().catch((e) => {
            console.log('caught error');
        }),
    ]);
}

Then this catch clause does catch the error.
My questions are:

  1. Why does it happen?
  2. Does it mean that when working with Promise.all i must define a .catch(...) function to every promise I pass to Promise.all otherwise if any promise will throw an exception is won't be caught anywhere and essentially crash my application?

Thanks

答案1

得分: 3

catch 子句未捕获错误。为什么会这样?
你没有等待任何内容,所以你只会捕获到同步错误。如果你想要使用 try/catch 捕获一个 Promise 拒绝,你必须 await 该 Promise。Promise.all 创建一个 Promise,所以请 await 它。

try {
  await Promise.all([funcThatThrowsError()]);
} catch (error) {
  console.log('捕获到错误');
}
英文:

> The catch clause doesn't catch the error. Why is that?

You aren't awaiting anything, so the only errors you will catch are synchronous errors. If you want to catch a promise rejection with try/catch, you must await that promise. Promise.all creates a promise, so await that.

try {
  await Promise.all([funcThatThrowsError()]);
} catch (error) {
  console.log('error caught');
}

huangapple
  • 本文由 发表于 2023年8月4日 22:58:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76837083.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定