Track JavaScript Errors with Google Analytics

By  on  

Google Analytics has always been more than a hit counter and demographic tool -- you could build a career out of being a Google Analytics analyst.  You can measure ad campaign effectiveness, track how far into a desired page flow (think advertisement to cart to checkout) users get, and set browser and locale support based your user's information.

But that's all stuff for the suits, not us devs.  What us nerds can use Google Analytics for, however, is error tracking via custom events.  Here's a quick look at how I've implemented error checking in analytics:

// Track basic JavaScript errors
window.addEventListener('error', function(e) {
    _gaq.push([
        '_trackEvent',
        'JavaScript Error',
        e.message,
        e.filename + ':  ' + e.lineno,
        true
    ]);
});

// Track AJAX errors (jQuery API)
$(document).ajaxError(function(e, request, settings) {
    _gaq.push([
        '_trackEvent',
        'Ajax error',
        settings.url,
        e.result,
        true
    ]);
});

Now when you go into Google Analytics, you can view the custom event information along with other site stats.  Of course you'll tell the marketing people those aren't really error, they're features, but that's another story.  Consider using Google Analytics for to track site errors -- you can thank me later.

Recent Features

  • By
    Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

  • By
    Conquering Impostor Syndrome

    Two years ago I documented my struggles with Imposter Syndrome and the response was immense.  I received messages of support and commiseration from new web developers, veteran engineers, and even persons of all experience levels in other professions.  I've even caught myself reading the post...

Incredible Demos

Discussion

  1. Andrey from Qbaka (javascript error monitoring) here.

    It’s easy to track js errors with google analytics, but there are problems with this way of tracking, too.
    The main problem is grouping: you will get millions of events from different users, browsers (every browser reports errors with different message), and languages (because IE reports in local languages).

    You will not get much useful data like stacktraces or user actions proior to the error from Google Analyitcs.
    However there are javascript error tracking services out there, that solve this problem and provide a lot of additional data, metrics and features to make tracking convenient. Consider trying one of such tools.

    At Qbaka (sorry for marketing, but everyone is free to compare our tool to others) we have smart error groping, track user actions to show how to reproduce error, filter out the noise and show you how many users were affected (and show exact users), support source maps and much more. It’s free for small projects, may be a valuable alternative to Google Analytics tracking.

  2. We’ve been doing this as well at work, but there’s one thing we found you’ll want to change here.

    _trackEvent has a fifth parameter, namely “nonInteractive”, as you can see: https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide

    It’d be best to pass true as the fifth param, otherwise any errors being tracked this way will affect the bounce rate metrics on your site; as far as I know, an “interactive” event tracked after a pageview makes GA consider it a non-bounce. If a JS error occurs right after pageload, and the user then closes the page, it won’t register as a bounce.

    Other than that, definitely a useful snippet if you don’t have the means to splurge on new relic for client-side!

    • Awesome, I’ll add that last param — thank you!

    • neiker

      I try this, but when last param is added, I didnt see the request to analytics..
      This works:

      _gaq.push(['_trackEvent', 'JavaScript Error', 'test tracking', 'file:10' ]);

      This doesn’t:

      _gaq.push(['_trackEvent', 'JavaScript Error', 'test tracking', 'file:10', true ]);
  3. I think I will thank you now. THANK YOU!

  4. Also, check it out, here is the list of approaches we use for js error tracking, you will like it:
    http://blog.qbaka.com/post/81596992555/getting-maximum-from-javascript-error-tracking

  5. nulll

    I tried to track errors with Analytics but it’s to noisy. You’ll get JS errors caused by browser, by viruses, by antiviruses, by addons…

  6. Kris O.

    This is great!

    Here is a Gist with cross-browser event listener, Universal Analytics and non-interaction set to avoid bounce-rate: https://gist.github.com/KrisOlszewski/10287367

    • Adam

      Since all major browsers (and all versions in use) support window.onerror, what is the benefit of first trying newer methods such as addEventListener, and attachEvent before falling back to onerror?

    • @Adam : because it’s the way forward.

      Adding event listeners lets you attach multiple events to the same handler. So if you had another error handler (perhaps showing a message to the user) it would work in modern browsers and not be replaced by this window.onerror.

    • using only window.onerror will be suffice.

  7. Micke

    Hmm I think you’ll have to add the “value” parameter too, which is normally is the fourth parameter after “category”, “action”, “label”.
    If I’m not mistaken, now you pass a boolean to the “value” param, which only accepts integers (maybe Boolean will be counted as 1, don’t know) or the event will fail.
    The boolean nonInteraction should come last…

    Not sure if I can post a link here, but I’ll try :)
    https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiEventTracking

  8. Kris O.

    @Micke Google is smart enough to check for argument type and act accordingly. Value parameter is not required. Here is a good overview: https://developers.google.com/analytics/devguides/collection/analyticsjs/events#implementation

  9. jylauril

    FYI: Universal Analytics has a specific event for exception tracking:
    https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#exception

  10. Micke

    @Kris O.

    Hmm interesting, thanks. I messed up some of my event tracking by passing an invalid value as, ehrm, value. I tend to be extra careful now… :)

  11. Rob M.

    I implemented this on a very popular site 2 years ago, here is what we learned:
    1) you are going to get a lot of useless garbage (“unknown error on line 0 of file 0” type stuff)
    2) Be careful with this if you have a high traffic site and are using other events, Google has a hard limit on the number of custom events you can track in a day (sorry, don’t have the number handy)
    3) randomly sampling errors paired down the data quite a bit

  12. Eric

    Eric from http://trackjs.com here. We love Google Analytics too, but we think a purpose-built JavaScript error tracker can add quite a bit of value. Our team has collectively rolled our own JS logging enough times that we figured it might be time to provide a nice turn-key solution, and solve a whole bunch of the cross-browser and analytics problems once and for all :)

    • Kristin

      Whoa, that’s really cool how it records clicks and ajax!

  13. Paolo Priotto

    The abovementioned error tracking services (qbaka, errorception and so forth) most probably being worth their money, we’re fine with GA since aroudn 8 months now, it has helped us a lot, and missing error grouping was not that big an issue for us. Our product is a single-page webapp that runs almost solely on webkit-based mobile browsers.

  14. What about sending “exception”. It seems to fill that purpose.
    https://developers.google.com/analytics/devguides/collection/analyticsjs/exceptions

      try {
        // try some code
      } catch(err) {
        ga('send', 'exception', {
          'exDescription': err.message,
          'exFatal': true,
          'appName': APP_NAME,
          'appVersion': APP_VERSION,
          'line': err.file,
        });
      }
    
    • Adam

      At this time, I would not recommend using UA ‘exceptions’ as they are not reported by default on the UA web interface.

  15. Andrew

    Statvoo Analytics (statvoo.com) does this for you automatically.

  16. Great solution, nice and clear. The business that I work with has been looking for something exactly like this.

  17. I’ve just blogged about this, with an updated code for analytics.js (Universal Analytics) here: https://franciskim.co/2016/01/19/free-javascript-ajax-error-monitoring-via-google-analytics/

  18. Fizer here from https://www.atatus.com/

    Google analytics is a simply way to get started with error tracking. However during production we might need

    1. Stacktraces which will help to debug the exact issue.
    2. The user actions that leads to the error. This will help in reproducing the issues at dev end.
    3. We might need to filter errors across various dimensions, such as users, URLs, tags, browsers, browserVersions etc.

    In Atatus you could drill down and filter errors such as only the ones that occur on IE9 or Chrome or Mobile.

    Atatus also supports Real User monitoring by which you can monitor the performance of your application. Also you can track page load time, AJAX requests and your transactions (eg: Checkout, Signup) performances

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!