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