I'm trying to implement an error handling that when a function raises an error, the calling function should catch that error and add some information to it, in order to make the problem easier to understand. In the example below, I try to explain my doubts. The first and second functions are called by third, and each one of them generates different errors, with different information. I would like the third function to be able to catch these errors and attach some information to them (the way the example is currently implemented I lose the information that first and second attached to the error).
class FirstError extends Error {
constructor(msg, num) {
super(msg);
this.num = num;
}
}
class SecondError extends Error {
constructor(msg, str) {
super(msg);
this.str = str;
}
}
class ThirdError extends Error {
constructor(msg, arg) {
super(msg);
this.arg = arg;
}
}
function first(num) {
throw new FirstError('First error', num);
}
function second(num) {
throw new SecondError('Second error', num.toString());
}
function third(fn) {
try {
fn(25);
} catch (error) {
throw new ThirdError('Third error', fn);
}
}
try {
third(first);
third(second);
} catch (error) {
console.log(error);
console.log(error instanceof Error);
console.log(error instanceof FirstError);
console.log(error instanceof SecondError);
console.log(error instanceof ThirdError);
console.log(error.message);
console.log(error.stack);
}
I also understand that I could test the instances of the error received on third, as the example below. However, as I will have several functions returning errors, this approach would be uninteresting as I would be left with too many tests and would have to update the third function with each new type of error added.
function third(fn) {
try {
fn(25);
} catch (error) {
if (error instanceof FirstError) {
throw new ThirdError('Third error', fn);
} else if (error instanceof SecondError) {
throw new ThirdError('Third error', fn);
}
}
}
Any ideas how to solve this issue?
You can pass the original error to the ThirdError. Then you can access that error, for example
...
class ThirdError extends Error {
constructor(msg, ...args) {
super(msg);
this.arg = args[0];
this.innerError = args.slice(1);
}
}
...
function third(fn) {
try {
fn(25);
} catch (error) {
throw new ThirdError('Third error', fn, error);
}
}
Output:
ThirdError: Third error
...,
innerError: [
FirstError: First error
... {
num: 25
}
]
}
...