英文:
Promise.all inside try-catch block - error not caught
问题
我在SoF上看到一些类似的帖子,但它们似乎不是完全相同的东西。
我对JavaScript还不太熟悉,所以可能漏掉了一些明显的东西。
以下是翻译好的代码部分:
在第一个示例中,catch
子句按照我期望的方式运行,也就是说它真正捕获了funcThatThrowsError
中抛出的错误。
然而,在第二个示例中,catch
子句未捕获错误。为什么会这样呢?
请注意,如果将上面的示例更改为以下方式:
那么这个catch
子句确实捕获了错误。
我的问题是:
- 为什么会发生这种情况?
- 这是否意味着当使用
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:
- Why does it happen?
- Does it mean that when working with
Promise.all
i must define a.catch(...)
function to every promise I pass toPromise.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 await
ing 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');
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论