2

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.