error handling - Javascript Try Catch vs Catch chain - Stack Overflow

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

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?

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?

Share Improve this question asked Nov 18, 2019 at 5:21 LuffyLuffy 4015 silver badges10 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 8

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 bee 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);
    }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742321553a4421914.html

相关推荐

  • error handling - Javascript Try Catch vs Catch chain - Stack Overflow

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

    10小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信