javascript 使用 JS 检测所有 JS 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20534457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
detect all JS errors, using JS
提问by markasoftware
I know this has probably been asked before, but I can't find where:
我知道之前可能已经问过这个问题,但我找不到在哪里:
I know you can detect JS errors using extensions in stuff, but is there any way to detect ALL errors using JavaScript and display an alert whenever there is one?
我知道您可以使用扩展来检测 JS 错误,但是有没有办法使用 JavaScript 检测所有错误并在出现警报时显示警报?
回答by Sukima
In the browser define the window.onerror
function. In node attached to the uncaughtException
event with process.on()
.
在浏览器中定义window.onerror
函数。在附加到uncaughtException
事件的节点中process.on()
。
This should ONLYbe used if your need to trap all errors, such as in a spec runner or console.log/ debugging implementation. Otherwise, you will find yourself in a world of hurt trying to track down strange behaviour. Like several have suggested, in normal day to day code a try / catch
block is the proper and best way to handle errors/exceptions.
这应该仅在您需要捕获所有错误时使用,例如在规范运行程序或 console.log/调试实现中。否则,你会发现自己处于一个痛苦的世界,试图追踪奇怪的行为。就像一些人建议的那样,在正常的日常代码中,try / catch
块是处理错误/异常的正确和最佳方式。
For reference in the former case, see this (about window.error in browsers)and this (about uncaughtException in node). Examples:
对于前一种情况的参考,请参阅this (about window.error in browsers)和this (about uncaughtException in node)。例子:
Browser
浏览器
window.onerror = function(error) {
// do something clever here
alert(error); // do NOT do this for real!
};
Node.js
节点.js
process.on('uncaughtException', function(error) {
// do something clever here
alert(error); // do NOT do this for real!
});