使用JS检测所有JS错误

mar*_*are 12 javascript error-handling

我知道之前可能已经问到这个问题,但我找不到:

我知道你可以使用扩展来检测JS错误,但有没有办法使用JavaScript检测所有错误并在有错误时显示警告?

Suk*_*ima 22

在浏览器中定义window.onerror函数.在附加到uncaughtException事件的节点中process.on().

这应该被使用,如果您需要捕获所有的错误,如在规范跑步者或执行console.log /调试实现.否则,你将发现自己处于一个伤害的世界,试图追查奇怪的行为.像几个人建议的那样,在正常的日常代码中,try / catch块是处理错误/异常的正确和最佳方式.

在前一种情况下的参考,请参阅此(关于浏览器中的window.error)此(关于节点中的uncaughtException).例子:

浏览器

window.onerror = function(error) {
  // do something clever here
  alert(error); // do NOT do this for real!
};
Run Code Online (Sandbox Code Playgroud)

Node.js的

process.on('uncaughtException', function(error) {
  // do something clever here
  alert(error); // do NOT do this for real!
});
Run Code Online (Sandbox Code Playgroud)