首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我在一些遗留代码中看到了几个catch块。这有什么意义吗?

我在一些遗留代码中看到了几个catch块。这有什么意义吗?
EN

Stack Overflow用户
提问于 2020-10-26 14:42:16
回答 3查看 55关注 0票数 1

在我目前的项目中,我看到了一些奇怪的代码结构,看起来像这样:

代码语言:javascript
复制
  async_api_call_with_throw_errors //pseudocode
    .then(() => async_call_with_throw_errors) //pseudocode
    .then(() => async_call_with_throw_errors) //pseudocode
    .then(() => async_call_with_throw_errors) //pseudocode
    .then(() => async_call_with_throw_errors) //pseudocode
    .catch((e) => {
        Sentry.captureException(e)
        if (e?.validateError) {
         //some actions
        } else {
          dispatch({ type: errorOccurred, errorText: e?.message, fatalError: false })
        }
      })
    .catch(e => {
      Sentry.captureException(e)
      dispatch({ type: errorOccurred, errorText: e, fatalError: false })
    })

如果" catch“块捕获了几种错误类型,这是可以的,但是在"then”块之后有两个具有相同错误的"catch“块有意义吗?

我不这么认为。但是也许我不知道关于try...catch的一些重要的事情?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-10-26 14:56:21

如果前面的catch抛出一个错误,然后由随后的catch捕获,则可以使用多个catch。看一下下面的代码。

代码语言:javascript
复制
const promise1 = new Promise((resolve, reject) => {
  throw 'Uh-oh!';
});

promise1.catch((error) => {
  console.error(error);
  throw "Error was caught!"
}).catch(err => {
    console.error(err)
})
// Expect Output:
//  > Uh-oh!
//  > Error was caught!

希望这能消除一些疑问。

票数 2
EN

Stack Overflow用户

发布于 2020-10-26 14:55:49

捕获并不都是为了同样的尝试。最后一个陷阱是try块。但第一个陷阱是promise链。

代码语言:javascript
复制
try {
-------
.catch(e => {
  Sentry.captureException(e)
  dispatch({ type: errorOccurred, errorText: e, fatalError: false })
})

承诺的区块是,

代码语言:javascript
复制
async_api_call_with_throw_errors //pseudocode
.then(() => async_call_with_throw_errors) //pseudocode
.then(() => async_call_with_throw_errors) //pseudocode
.then(() => async_call_with_throw_errors) //pseudocode
.then(() => async_call_with_throw_errors) //pseudocode
.catch((e) => {
    const eventId = Sentry.captureException(e)
    if (e?.validateError) {
     //some actions
    } else {
      dispatch({ type: errorOccurred, errorText: e?.message, fatalError: false })
    }
  })

现在,我们不应该对这样的异步调用使用try/catch。如果你想在异步操作周围使用try/catch块,你应该使用await来调用async方法,并且应该没有promise解析链。代码应该写成,

代码语言:javascript
复制
try {
  await async_api_call_with_throw_errors;
  await async_api_call_with_throw_errors;
  await async_api_call_with_throw_errors; 
    .....
} catch (error) {
   handle errors
}

顺便说一句,你应该确保你想要使用的异步/等待函数也是一个异步函数。

票数 2
EN

Stack Overflow用户

发布于 2020-10-26 14:57:17

如果第一个catch抛出一个错误,它应该可以工作,尽管我不确定为什么有人会这样做。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64532506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档