Track Angular Exceptions Automagically In Google Analytics


track angular exceptions in google analytics
We use AngularJS at LunaMetrics as part of the stack for our internal toolset. One of the things we wanted to do early on was track exceptions thrown in the application with Google Analytics, something I’ve always advocated for. The project I contribute to, Angulartics, DOES support error tracking, but it’s up to you to invoke it. I wanted something more automagic, so I set about digging in the Angular documentation to see what I could do.

After doing a little research, I knew that Angular handled exceptions internally by way of the $exceptionHandler service. The documentation spelled out that replacing the service was a viable option for changing the way exceptions were handled; I didn’t want to lose the default behavior, though, so I kept looking.

The method I ended up settling on was to use a service decorator. Service decorators are called during service instantiation, and are passed in the original service instance, annotated $delegate in the docs. You can then modify, extend, replace, or patch that service to your hearts content.

Using this approach, I extended the existing $exceptionHandler to push data about the exception into the dataLayer. I’m using Angulartics in my project, so I chose to make use of the trackException method – ultimately, this is just a fancy wrapper for an Event that gets sent to Google Analytics.

EDIT: Since this post was initially drafted, this functionality was introduced to Angulartics. Read more here. Shoutout to Oded Niv for the PR. If you’d like automagic exception tracking without using the Angulartics library, you can use the below code as a template – just replace $analyticsProvider with the provider for your own Analytics wrapper, or (shame on you) just access the global ga/_gaq objects directly.

You can easily swap out the code on lines 23:26 with a different way of transmitting the data to Google Analytics. If you’re using Angulartics with Google Tag Manager, make sure that you’ve got your Angulartics Event tag configured (hint: import the container JSON instead of configuring it manually).

Once you’ve got it in place, any time an exception is emitted from an Angular expression, it will be automatically sent off to Google Analytics for you to analyze/respond to. Plus, you’ll get all the associated hit data that Google Analytics collects, like browser type, device, and browser version, which can help with reproducing any tricky bugs.

Got a different approach? Share it in the comments.

Dan Wilkerson is a former LunaMetrician and contributor to our blog.

Contact Us.

Follow Us



We'll get back to you
in ONE business day.
Our Locations
THE FOUNDRY [map] LunaMetrics

24 S. 18th Street
Suite 100

Pittsburgh, PA 15203


4115 N. Ravenswood
Suite 101
Chicago, IL 60613


2100 Manchester Rd.
Building C, Suite 1750
Wheaton, IL 60187