【发布时间】:2011-11-22 07:34:32
【问题描述】:
我有一点 JavaScript (Jquery Tools' Overlay) 可能会在放置在不正确使用它的页面上时引发异常,我正在尝试优雅地处理它。
我有一个通用的 window.onerror 处理程序来挽救这些错误并将它们报告回服务器,但这并没有被触发。
我也无法围绕此代码包装 try/catch,因为它作为远程脚本包含在 HTML 中。
关于如何挽救外部脚本引发的错误的任何想法?
更新:示例如下。我应该纠正自己,window.onerror 确实被触发了,但是脚本没有继续运行(在示例中,警报永远不会发出警报)。
<html>
<script type="text/javascript">
window.onerror = function(e){ console.log("caught error: "+e); return true;}
</script>
<body>
<!-- this is the line in the dom that causes the script to throw -->
<a rel="nofollow"></a>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("jquery", "1.4.1");</script>
<script src="http://cdn.jquerytools.org/1.2.5/tiny/jquery.tools.min.js"></script>
<script type="text/javascript">
//this code will throw an error in jquery tools
$("a[rel]").overlay();
alert("it's ok, I still ran.");
</script>
</body>
</html>
【问题讨论】:
-
您的
window.onerror是否在引发错误之前定义?如果没有,它将无法正常工作。
标签: javascript exception-handling