在外部脚本文件中捕获JavaScript错误 [英] Catch a javascript error in an external script file
问题描述
我有一点JavaScript( Jquery Tools'Overlay ),可能会抛出当它丢失在使用它不正确的页面上时,我正在尝试优雅地处理它。
我有一个通用的window.onerror处理程序来拯救这些错误,并将其报告回服务器,但是这并没有被触发。
我也不能包围这个代码的try / catch,因为它被作为远程脚本包含在HTML中。
关于如何解决外部脚本引发的错误的任何想法?
更新:这是一个例子。我应该纠正自己,window.onerror 被触发,但脚本不会继续运行(在该示例中,警报从不警报)。
< HTML>
< script type =text / javascript>
window.onerror = function(e){console.log(catch error:+ e); return true;}
< / script>
< body>
<! - 这是导致脚本抛出的dom中的行 - >
< a rel =nofollow>< / a>
< script type =text / javascriptsrc =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>
//这个代码会在jquery工具中抛出一个错误
$(a [rel]))。overlay();
alert(没关系,我还跑。);
< / script>
< / body>
< / html>
在加载任何其他脚本之前定义错误处理程序执行。
< script> window.onerror = function(e){}< / script>
< script src =external.js>< / script>
< script>
function ole(){alert(Hi!)}
ole();
< / script>
当您的脚本包含语法错误时,错误处理程序将不会被调用:
< script> window.onerror = function(e){alert(?)}
< script>
!@ //错误不会被捕获。
< / script>
I have a bit of JavaScript (Jquery Tools' Overlay) which may throw an exception when dropped on a page that uses it incorrectly, and I'm trying to handle it gracefully.
I have a general window.onerror handler to rescue these errors and report them back to the server, however that's not getting triggered.
I also cannot wrap a try/catch around this code, as it's being included as a remote script in HTML.
Any ideas on how you can rescue errors that an external script throws?
UPDATE: Here's the example. I should correct myself, window.onerror does get triggered, however the script does not continue running (in the example, the alert never alerts).
<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>
Define the error handler before any other script is loaded/executed.
<script>window.onerror = function(e){}</script>
<script src="external.js"></script>
<script>
function ole(){alert("Hi!")}
ole();
</script>
When your script contains a syntax error, the error handler won't be called though:
<script>window.onerror=function(e){alert("?")}
<script>
!@ //The error won't be caught.
</script>
这篇关于在外部脚本文件中捕获JavaScript错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!