Javascript: Track Errors with Google Analytics (analytics.js)

      I came across an article by David Walsh and just wanted to expand on the topic. When implementing this feature watch out for the differences between analytics.js and ga.js. The code below is works with analytics.js. Another thing to be aware of is that some errors will be created from Adblocker. I thought of adding the logic but I didn't want to leave it up to chance that I might accidentally ignore some real errors. Instead what you can did is just filter it in Google Analytics and aggregate against with the number hits.

(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', 'YOURID', 'auto');
ga('send', 'pageview');        
window.addEventListener('error', function (e) {
    ga('send', 'event', 'Javascript Error', e.filename + ':  ' + e.lineno, e.message); 
});
 
$(document).ajaxError(function (e, request, settings) {
    ga('send', 'event', 'API Error', settings.url, e.result);                 
});


Using in Google Analytics
     Under Real-Time or Behavior look at Events -> Overview, for testing purposes use the real-time at least once to make sure everything is working properly.

Notes
     With David Walsh's snippet it includes jquery ajax calls but what about angular http calls? I'm still looking at this and for ways to test it.

Resources

Popular posts from this blog

Nginx Best Practices Extended

Installing Windows on Acer chromebook 15 cb3-532

Entity Framework: ToListAynsc & WhereAsync