Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error breaking out of a try/catch statement

As i was programming a NPM package, i came to need of a try{}catch{} statement, but error sometimes breaks out of try{} part and terminates the entire process.

As try{}catch{} is used to catch errors from try{} part and handle them with the catch{} part, I expected that the error will be caught and passed to catch{}, but when a function returns an error using return, not throw statement, the error breaks out. I tried different call methods, such as .call(...) or .apply(...), but the problem persists.

This passes:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let result;

let throwError = () => throw new Error("I didn't break out!");

try {
  let res = throwError();
  result = res;
} catch(err) {
  result = {
    message: err.message,
    name: err.name
  }
}

result; // {name: "Error", message: "I didn't break out!"}

This fails:

let result;

let returnError = () => new Error("I broke out!")

try {
  let res = returnError(); // Error: I broke out!
  result = res;
} catch(err) {
  result = {
    message: err.message,
    name: err.name
  }
}

>Solution :

There’s no problem here. If you want to catch an error being throw, try/catch will do that. If you want to catch an error being returned, you need a different check for that.

let result;

let returnError = () => new Error("I broke out!")

try {
  let res = returnError();
  
  if (res instanceof Error) {
    throw res;
  }

  result = res;
} catch(err) {
  result = {
    message: err.message,
    name: err.name
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading