在以下代码中,(玩具)函数f1
和f2
来自库,因此我无法更改它们。
function f1() { // cannot change this
var x;
alert(x.y); // throws an error because x is undefined
}
function f2() { // cannot change this either
setTimeout(f1, 1000); // creates an asynchronous timeout
}
现在我想抓住错误:
try { // does not work because of the asynchronous environment
f2();
} catch (error) {
console.log('caught: ' + error);
}
但我知道这不起作用,因为setTimeout
创建的环境不是指定try-catch块的环境。
还有其他可能性来捕获错误吗?
答案 0 :(得分:0)
您可以通过覆盖f1
功能...
// original functions -- this is all the code you can't modify
function f1() {
throw "Oh no - an exception!";
}
function f2() {
try {
setTimeout(f1, 1000);
}
catch(e) {
alert(e + " - this is handled in the original code");
}
}
// end of the code you can't modify
// keep a reference to the original f1 function
var __f1 = f1;
// override the original f1 function
var f1 = function() {
try {
// this calls the original version of f1(), along with any parameters
return __f1.apply(this, arguments);
}
catch(e) {
alert(e + " - this is handled in your new code");
}
};
// execute...
f2();