Luffy
Luffy

Reputation: 401

Javascript Try Catch vs Catch chain

I recently ran into a Javascript problem catching errors and thus crashing when exception thrown.

I had to change this to:

try {
  funcReturnPromise().then()
} catch (e) {
  ...
}

Couldn't find a decent explanation for it, any JS wizards available to enlighten a JS peasant?

Upvotes: 3

Views: 5346

Answers (1)

jfriend00
jfriend00

Reputation: 707326

If funcReturnPromise() can throw synchronously (which functions that return promises should generally never do), then you do have to catch that synchronous exception with try/catch as you discovered when using regular .then().

This is one place where async functions can hep you. For example, if you declare funcReturnPromise as async, then the synchronous exception it throws will automatically become a rejected promise and the caller won't ever be exposed to a synchronous exception.

Or, if the caller (your code here) uses await, then you can catch both sycnhronous exceptions and rejected promises with the same try/catch.

So, for example, you could do this:

async function myFunc()
    try {
      let result = await funcReturnPromise();
      console.log(result);
    } catch (e) {
        // this catches both a rejected promise AND
        // a synchronously thrown exception
        console.log(e);
    }
}

Upvotes: 8

Related Questions