Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  191] [ 1]  / answers: 1 / hits: 22255  / 13 Years ago, wed, september 21, 2011, 12:00:00

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>

More From » exception

 Answers
21

Define the error handler before any other script is loaded/executed.


<script>window.onerror = function(e){alert(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 (edit: in some older browsers):


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

[#89986] Tuesday, September 20, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
myrap

Total Points: 407
Total Questions: 105
Total Answers: 109

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
myrap questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Wed, Jan 15, 20, 00:00, 4 Years ago
Thu, Oct 24, 19, 00:00, 5 Years ago
Thu, Oct 3, 19, 00:00, 5 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;