使用嵌套的 try / catch 块时错误处理不正确

Incorrect error handling when using nested try / catch blocks

我使用 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" 似乎所有错误都传播到最外层的捕获?

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

在您的代码中,检查第一个 try 块内是否发生异常。如果是这样,内部try将不会被执行。

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")
  }

这也是一种可能的情况:

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")
  }

希望这对您有所帮助:)