How to Log JavaScript Errors


One of the best ways I have found to log javascript errors is to use Google Analytics. In this blog post I will show you a few ways to use Google to log your errors.

NOTE: Make sure you have an Analytics account before you start. http://www.google.com/analytics

So let’s look at some example code. Make sure you have this snippet before any of your javascript. This should go in your head tag.

<script type="text/javascript">
    var _gaq = _gaq || [];
</script>

This does 2 things for us. First it allows us to access the variable within any of our code. The second is it sets that variable to an array.

So I’m a big fan a jQuery and use it a lot on almost all of the projects I use. Most of the projects I work on are heavy AJAX web applications. Look at this example.

$.ajax("foobar-script.php")
    .fail(function(){
        // Something screwed up
        _gaq.push(['_trackEvent', 'JavascriptError', 'AJAX Error']);
    });

This uses Event Tracking to allow you to see those errors in your reports. That’s really all there is to it. You can now drill down into some stats and see more info about your user. You can even add more detail to the ajax error.