Search code examples
javascripterror-handlingtry-catchpropagation

Incorrect error handling when using nested try / catch blocks


I have error handling set up using try/catch blocks, which in its simplified form looks like this

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

And the issue is, whenever I expect "Api Error" to be returned I get "Unknown Error" it seems like all errors are propagated to the outermost catch?

Is there a way to avoid this or another approach that allows for nested error handling?


Solution

  • 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 :)