gpt4 book ai didi

javascript - 在外部脚本文件中捕获 javascript 错误

转载 作者:数据小太阳 更新时间:2023-10-29 04:16:17 25 4
gpt4 key购买 nike

我有一些 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>

最佳答案

在加载/执行任何其他脚本之前定义错误处理程序。

<script>window.onerror = function(e){alert(e);}</script>
<script src="external.js"></script>
<script>
function ole(){alert("Hi!")}
ole();
</script>

当您的脚本包含语法错误时,将不会调用错误处理程序(编辑:在某些较旧的浏览器中):

<script>window.onerror=function(e){alert(e);}</script>
<script>
!@ //The error won't be caught (at least not in older browsers)
</script>

关于javascript - 在外部脚本文件中捕获 javascript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7506444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com