首页 > 解决方案 > 使用嵌套的 try / catch 块时错误处理不正确

问题描述

我使用块设置了错误处理try/catch,其简化形式如下所示

  try {
    // .. Some application logic

    try {
      // .. some async api code
    } catch (e) {
      throw new Error("Api Error")
    }

    return true;

  } catch (e) {
    throw new Error("Unknown Error")
  }

问题是,每当我期望返回“Api Error”时,我会得到“Unknown Error”,似乎所有错误都传播到最外层的捕获?

有没有办法避免这种或其他允许嵌套错误处理的方法?

标签: javascripterror-handlingtry-catchpropagation

解决方案


In your code, check if exception is happening inside the first try block. If so, the inner try won't be executed.

try {
    // .. Some application logic
    // exception occurs here
    // below code is not executed and the control is given to catch block
    try {
      //this did not execute
      // .. some async api code
    } catch (e) {
      throw new Error("Api Error")
    }

    return true;

  } 
  catch (e) {
    //control came here
    throw new Error("Unknown Error")
  }

This is also a possible case:

try {
    // .. Some application logic
    // no exceptions occur here
    // below code is executed
    try {
      //this did not execute
      //exception here
      // .. some async api code
    } catch (e) {
      //control came here and this threw APIerror
      throw new Error("Api Error")
    }
    //this did not execute as the previous catch block raised another exception
    return true;

  } 
  catch (e) {
    //control came here
    throw new Error("Unknown Error")
  }

Hope this helps :)


推荐阅读