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