Track JavaScript, AngularJS and jQuery errors with Google Analytics

Google Analytics is the most popular website statistics service. It is used for many purposes: from tracking visitors and sessions to campaigns and events.

Ability to track any events provides us possibility to send and track any data in Google Analytics. One of the most useful in that case for web developers might be errors analytics.

So far Google proposes 2 ways of tracking events:

  1. Classic ga.js with the for tracking like _gaq.push(...)
  2. Newer analytics.js has syntax ga('send', ...) and is part of the new Universal Analytics

Let's provide JavaScript, AngularJS and jQuery errors checking.

Classic ga.js

This way works when you include Google Analytics in the next way:

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['_trackPageview']);
(function () {
    var ga = document.createElement('script');
    ga.type = 'text/javascript';
    ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(ga, s);
})();

JavaScript errors

The following code sends to GA data about all thrown JS errors (error message and place when error appeared). navigator.userAgent provides info about the browser to simpify detecting problems in difficult cases.

// Pure JavaScript errors handler
window.addEventListener('error', function (err) {
    var lineAndColumnInfo = err.colno ? ' line:' + err.lineno +', column:'+ err.colno : ' line:' + err.lineno;
    _gaq.push([
        '_trackEvent',
        'JavaScript Error',
        err.message,
        err.filename + lineAndColumnInfo + ' -> ' +  navigator.userAgent,
        0,
        true
    ]);
});

AngularJS exceptions handler

AngularJS delegates all uncaught exceptions to $exceptionHandler service.

// AngularJS errors handler
angular.module('loggerApp')
        .config(function ($provide) {
            $provide.decorator("$exceptionHandler", function ($delegate) {
                return function (exception, cause) {
                    $delegate(exception, cause);
                    _gaq.push([
                        '_trackEvent',
                        'AngularJS error',
                        exception.message,
                        exception.stack,
                        0,
                        true
                    ]);
                };
            });
        });

jQuery

jQuery errors

jQuery provides util method .error() which is advised for developers to use for exceptions.

// jQuery errors handler (jQuery API)
jQuery.error = function (message) {
    _gaq.push([
        '_trackEvent',
        'jQuery Error',
        message,
        navigator.userAgent,
        0,
        true
    ]);
}

jQuery AJAX errors handler

Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event.

// jQuery AJAX errors handler (jQuery API)
$(document).ajaxError(function (event, request, settings) {
    _gaq.push([
        '_trackEvent',
        'jQuery Ajax Error',
        settings.url,
        JSON.stringify({
            result: event.result,
            status: request.status,
            statusText: request.statusText,
            crossDomain: settings.crossDomain,
            dataType: settings.dataType
        }),
        0,
        true
    ]);
});

Modern analytics.js

You can use it when include the analytics like:

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXXXXX-X', 'auto');
ga('send', 'pageview');

Here is the manual about updating Event Tracking to Universal Analytics (analytics.js)

JavaScript errors

// Pure JavaScript errors handler
window.addEventListener('error', function (err) {
    var lineAndColumnInfo = err.colno ? ' line:' + err.lineno +', column:'+ err.colno : ' line:' + err.lineno;
    ga(
        'send',
        'event',
        'JavaScript Error',
        err.message,
        err.filename + lineAndColumnInfo + ' -> ' +  navigator.userAgent,
        0,
        true
    );
});

AngularJS exceptions handler

// AngularJS errors handler
angular.module('loggerApp')
        .config(function ($provide) {
            $provide.decorator("$exceptionHandler", function ($delegate) {
                return function (exception, cause) {
                    $delegate(exception, cause);
                    ga(
                        'send',
                        'event',
                        'AngularJS error',
                        exception.message,
                        exception.stack,
                        0,
                        true
                    );
                };
            });
        });

jQuery

jQuery errors

// jQuery errors handler (jQuery API)
jQuery.error = function (message) {
    ga(
        'send',
        'event',
        'jQuery Error',
        message,
        navigator.userAgent,
        0,
        true
    );
}

jQuery AJAX errors handler

// jQuery AJAX errors handler (jQuery API)
$(document).ajaxError(function (event, request, settings) {
    ga(
        'send',
        'event',
        'jQuery Ajax Error',
        settings.url,
        JSON.stringify({
            result: event.result,
            status: request.status,
            statusText: request.statusText,
            crossDomain: settings.crossDomain,
            dataType: settings.dataType
        }),
        0,
        true
    );
});

Demo

In the prepared demos all output from developer console is shown in special block under buttons.

You can generate errors and check in "Network" tab that for each error GA sends request to:

  1. ga.js - to http://www.google-analytics.com/__utm.gif?...
  2. analytics.js - to http://www.google-analytics.com/r/collect?...

Classic ga.js

Modern analytics.js

Checking analytics data in GA

In GA you can find two main reports for Events:

Real-Time Events

Common Events Report

0, true params in the end

These params mean respectively according the manual:

  • 0 - opt_value (default value is 0)

Detailed info about this param

  • true - opt_noninteraction (default value is false)

Is set to true to not affect the bounce rate. Here is the description in more details

Exceptions - Web Tracking (analytics.js)

Universal Analytics proposes other way to track exceptions- Exceptions - Web Tracking (analytics.js).

But after some research it appeared that report for it is not so easy to configure and even to find.