2016-09-06 46 views
0

我正在寻找一种解决方案,在该解决方案中,我可以捕获浏览器控制台中记录的所有错误(已处理/未处理)。JavaScript Capture处理错误

我知道关于window.onerrorwindow.addeventlistener('error', function(){})

上述代码仅捕获未处理的错误。我还需要捕获处理的错误。

例如:

function foo() { 
    var x = null; 
    try { 
    x.a = ""; 
    } catch (e) { 
    //Exception will be digested here. 
    } 

    var y = null 
    y.b = ""; 
} 

window.onerror = function() { 
    //Write logic for the errors logged in console. 
} 

foo(); 

在上面的例子try catch是存在的,所以我会得到错误仅适用于可变yx

是否有任何方法来聆听/捕获catch块?

谢谢

+0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#The_finally_clause –

+0

你可以这样做,当使用调试器。但不是来自JS本身。你为什么想这样做? – Oriol

+0

如果你真的想要,你可以抛出一个自定义错误后,将其传递给window.onerror。例如:https://fiddle.jshell.net/L29jv5fv/你想做什么? –

回答

0

尝试手动调用window.onerror。但请重新考虑改变您的方法。这是非常肮脏的。

window.onerror = function(msg, url, lineNo, columnNo, error) { 
    if (error === 'custom') { 
    console.log("Handled error logged"); 
    return true; 
    } 
    console.log("unhandled error") 
    return false; 
}; 

例的try/catch

var myalert = function() { 
    try { 
    console.log(f); 
    } catch (e) { 
    window.onerror('test',null,null,null,'custom'); 
    } 
    console.log("Gets here"); 
} 

https://fiddle.jshell.net/L29jv5fv/2/

0

现实情况是,如果一个异常被捕获,然后因为你的代码知道如何处理它是没有问题的。

在像Java这样的其他编程语言中,最好的做法是只捕获可处理的异常,并将其他所有内容抛到链上和/或映射到另一个可能对调用堆栈更有用的异常。

例如:

function foo() { 
    var x = null; 
    try { 
    x.a = ""; 
    } catch (e) { 
    //Exception will be digested here. 
    console.log("I am writing code here but still don't know how to proceed"); 
    throw new CustomError("Something was wrong"); 
    } 

    var y = null 
    y.b = ""; 
}