首页 > web前端 > js教程 > 正文

如何使用'window.onerror”事件有效地全局处理 JavaScript 错误?

Patricia Arquette
发布: 2024-10-26 21:09:02
原创
818 人浏览过

How can I effectively handle JavaScript errors globally using the `window.onerror` event?

使用全局事件机制进行有效的 JavaScript 错误处理

为了全局处理未定义的函数错误,利用 JavaScript 的全局事件机制有效捕获所有未捕获的错误

window.onerror 事件处理

为 window.onerror 事件实现一个事件处理程序,如下所示:

<code class="javascript">window.onerror = function(msg, url, line, col, error) {
  // Message, URL, line and column details
  // Note that col & error are new to HTML 5 and may vary across browsers.

  // Customize the error display or perform error reporting using AJAX, for instance:
  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/ajax/log_javascript_error');
  xhr.send(JSON.stringify({ msg, url, line, col, error }));
};</code>
登录后复制

< ;h2>window.onerror什么时候触发?

此事件触发时:

  • 未捕获的异常:抛出消息、调用未定义的函数,或跨越原始 iframe 内容窗口/文档错误。
  • 编译错误:语法错误,例如不匹配的括号、缺少分号或尝试编译非脚本参数。

浏览器支持

  • Chrome 13
  • Firefox 6.0
  • Internet Explorer 5.5
  • Opera 11.60
  • Safari 5.1

其他资源

  • Mozilla 开发者网络:[window.onerror](https:/ /developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror)
  • MSDN:[处理和避免网页错误第 2 部分:运行时错误](https://docs .microsoft.com/en-us/previous-versions/ms536764(v=vs.85))
  • [回归基础 – JavaScript onerror 事件](https://www.webdesignerdepot.com/2014/ 10/back-to-basics-javascript-onerror-event/)
  • [DEV.OPERA:使用 window.onerror 更好地处理错误](https://dev.opera.com/articles/better-error -handling-with-window-onerror/)
  • [窗口 onError 事件](https://www.html5rocks.com/en/tutorials/developertools/onerror/)
  • [使用onerror 事件来抑制 JavaScript 错误](https://stackoverflow.com/a/11712511)
  • [SO: window.onerror 不会在 Firefox 中触发](https://stackoverflow.com/q/5472601/ 123152)

以上是如何使用'window.onerror”事件有效地全局处理 JavaScript 错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!