最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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);
    }
}
发布评论

评论列表(0)

  1. 暂无评论