-2

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 Answers1

3

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');
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98