Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Try Catch vs Catch chain

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

  • funcReturnPromise().then().catch()

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?

like image 279
Luffy Avatar asked Jul 04 '26 11:07

Luffy


1 Answers

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);
    }
}
like image 88
jfriend00 Avatar answered Jul 06 '26 01:07

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!