我在一些基本的错误处理/捕获方面遇到了麻烦。如果我有以下代码:
function test() {
areThereErrors(sum(1,2));
areThereErrors(sumo(1,2));
}
function areThereErrors(value) {
console.log(value);
}
如何在第二次调用 areThereErrors 时捕获拼写错误中的错误?我的基本理解是我必须调用 test() 但不幸的是我只调用 console.log 3 一次,仅此而已。如果 sumo 抛出错误,我希望能够返回 true,因为 sumo 不是函数。
注意:问题的关键是,是否可以使用 areThereErrors 内的代码捕获错误?
最佳答案
The crux of the issue is, is it possible to catch the error with code WITHIN
areThereErrors
?
不会,因为在准备调用它时评估 areThereErrors
的参数时将会抛出错误,并且永远不会调用它。
但是,您可以通过向 areThereErrors
传递一个要执行的函数,使它按照您想要的方式工作。
function areThereErrors(fn) {
try { console.log(fn()); }
catch (e) { console.log("Oh, no, an error has been thrown"); return true; }
}
现在您可以将代码编写为
function test() {
areThereErrors(() => sum(1,2)));
areThereErrors(() => sumo(1,2)));
}
另一种替代方法是将 areThereErrors
制作为一个高阶函数,该函数将一个函数作为输入并返回另一个函数,该函数将对它的调用包装在 try/catch 中。方法是:
function areThereErrors(fn) {
return function() {
try {
return fn(...arguments);
} catch (e) {
return false;
}
};
}
现在您可以编写如下代码
function test() {
areThereErrors(sum)(1, 2);
areThereErrors(sumo)(1, 2);
}
关于javascript - 在另一个函数的参数中捕获函数中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35994733/