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.

{% highlight html %}

{% endhighlight %}

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][1].

So I’m a big fan a [jQuery](http://jquery.com) 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.

{% highlight javascript %}
$.ajax(“foobar-script.php”)
.fail(function(){
// Something screwed up
_gaq.push([‘_trackEvent’, ‘JavascriptError’, ‘AJAX Error’]);
});
{% endhighlight %}

This uses [Event][2] [Tracking][3] 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.

[1]: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array
[2]: https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide
[3]: https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiEventTracking