P is for Programming

Debugging JavaScript errors

January 6, 2010

I have noticed that quite a few developers are unaware of one of the simplest methods of finding JavaScript errors in your page.  JavaScript exposes an event handler that fires whenever a JavaScript error occurs in a page.  Using it we can suppress all JavaScript errors on the page or display an error dialog.

Example

Here is an example of using the onerror event:

<script type="text/javascript">
    window.onerror = function(msg, url, line) {
        alert("JavaScript error: " + msg + " on line " + line);
    }
</script>

Now if we make an obvious error like the following…

<script type="text/javascript">
    document.write("this should produce an error"
</script>

we’ll get a nice detailed error message.

Dialog

This works in Firefox 3 and IE 7.  For some reason this doesn’t work in Chrome (v2.0.172.37).  If you can shed some light on why this doesn’t work in Chrome please do so in the comments section below.

Keep in mind that you shouldn’t deploy this type of error handling into a production server – you might think about using a compiler directive so that the code only exists in Debug mode.

Happy coding.

Tags: JavaScript, web

  1. Anonymous says:

    Or you could just use firebug

  2. Offbeatmammal says:

    the reason is documented here….
    https://bugs.webkit.org/show_bug.cgi?id=8519 http://code.google.com/p/chromium/issues/detail?id=7771
    basically… people are too busy arguing semantics to actually provide something useful :( *

  3. Jaco Pretorius says:

    Thanks Offbeatmammal!

  4. Anonymous says:

    Hey bumped to this post while debugging a javascript error..Thanks a lot man..I was able to successfully debug an JS issue