Catch javascript error in external script file

I have some JavaScript ( Jquery Tools' Overlay ) that can throw an exception when deleted on a page that uses it incorrectly, and I'm trying to handle it gracefully.

I have a general window.onerror handler to repair these errors and send reports to the server, however this does not work.

I also cannot wrap try / catch around this code, as it is included as a remote script in HTML.

Any ideas on how you can save errors that are caused by an external script?

UPDATE . Here is an example. I have to fix myself, window.onerror is triggered, however the script does not continue to work (in the example, the warning never appears).

<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 ok, I still ran."); </script> </body> </html> 
+8
javascript exception-handling
source share
1 answer

Define an 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> 

If your script contains a syntax error, the error handler will not be called:

 <script>window.onerror=function(e){alert("?")} <script> !@ //The error won't be caught. </script> 
+5
source share

All Articles