As I was making a NPM package, I had to use a try/catch
statement, but noticed that the error is able to break out of the try{ … }
part and terminate 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 isn't caught and breaks out. I tried different function 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(); // Uncaught error: I broke out!
result = res;
} catch(err) {
result = {
message: err.message,
name: err.name
}
}
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
}
}