【发布时间】:2021-12-03 16:18:21
【问题描述】:
我正在尝试实现错误处理,当函数引发错误时,调用函数应捕获该错误并向其添加一些信息,以使问题更易于理解。在下面的例子中,我试图解释我的疑惑。 first 和second 函数由third 调用,它们各自产生不同的错误,具有不同的信息。我希望third 函数能够捕获这些错误并将一些信息附加到它们(示例当前实现的方式我丢失了first 和second 附加到错误的信息)。
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);
}
我也知道我可以测试在third 上收到的错误实例,如下例所示。但是,由于我将有几个函数返回错误,因此这种方法将无趣,因为我会留下太多测试,并且必须在添加每种新类型的错误时更新第三个函数。
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);
}
}
}
任何想法如何解决这个问题?
【问题讨论】:
标签: javascript typescript error-handling try-catch