As a developer, client-side errors can be a real pain. Developers usually do a good job logging server-side application errors, but often times ignore client-side errors. As the web evolves, we’re seeing more and more single page applications that are heavily reliant on client-side service calls using technologies like AJAX. This makes sites heavily dependent on JavaScript.
Google Tag Manager just released a new listener tag type, the ‘JavaScript Error Listener’. The JavaScript Error Listener will allow you to capture client-side errors that would otherwise be invisible to the server and log them to Google Analytics or another service of your own choosing. For my example, I’ll be logging JavaScript errors to Google Analytics as an event with the error itself as the event label. Bear in mind that the maximum size for an event label is 500 Bytes which will let us store 500 characters.
The first thing we need to do is add the JavaScript Error Listener to our tag container:
Now that we have the JavaScript Error Listener in place with a firing rule of ‘All Pages’, I’m going to publish a debug version of the container so I can inspect the gtm.PageError object that will be pushed to the data layer when a JavaScript error occurs. To do this, I’ve created a simple test page with a JavaScript error that results when the link is clicked because no function with that name exists. Once I opened the test page:
- I opened the Chrome developer tools
- Clicked the link on the test page to cause the JavaScript error
- Typed ‘dataLayer’ in the console to inspect the dataLayer and expanded the last item (most recently added) to see the contents of the gtm.pageError event.
Now I can see that the ‘gtm.errorMessage’ field is populated with some useful information about the uncaught exception. To log this to Google Analytics as an event, I’ll need to add a new tag in GTM with a firing rule of {{event}} equals gtm.pageError and create a new macro for the gtm.errorMessage object.
Here’s the rule to fire the GA event when an error occurs:
The macro to pull in the JavaScript error message:
and finally the GA event tag itself:
Now when a JavaScript error occurs on your site, you’ll be able to see them in your Google Analytics event reports:
To take this a step further, I’d suggest setting up custom alerts to send an email when JavaScript errors occur on your site.
Questions or comments? Get in touch with me on Google+ or leave a comment below.
Comments on this entry are closed.
Pingback: Capturing client-side javascript Errors | koding notes()