在外部脚本文件中捕获 javascript 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7506444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Catch a javascript error in an external script file
提问by Tom Lianza
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.
我有一些 JavaScript(Jquery 工具的 Overlay),当它放在错误使用它的页面上时可能会引发异常,我正在尝试优雅地处理它。
I have a general window.onerror handler to rescue these errors and report them back to the server, however that's not getting triggered.
我有一个通用的 window.onerror 处理程序来拯救这些错误并将它们报告给服务器,但这并没有被触发。
I also cannot wrap a try/catch around this code, as it's being included as a remote script in HTML.
我也无法围绕此代码进行 try/catch,因为它作为远程脚本包含在 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 doesget triggered, however the script does not continue running (in the example, the alert never alerts).
更新:这是示例。我应该纠正自己,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>
采纳答案by Rob W
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>