Logging Error Events with Google Analytics and GTM

Track and analyze JavaScript errors in real time with Google Analytics and GTM for better frontend debugging and user experience insights.

Ceyhun Enki Aksan
Ceyhun Enki Aksan Entrepreneur, Maker

WordPress to Grav migration process — previously published updates1 — also covers potential errors that may occur when viewing a web page, and how these errors can be displayed in Google Analytics.

If you’ve been following my posts for a long time, you’ll recall my earlier article titled Replacing/Hide Images with jQuery and Tracking. In that post, I focused on the error event triggered when an image fails to load, and resolved it using jQuery. Now, within the scope of this article, we’ll expand upon that solution and present the final findings in a viewable format via Looker Studio.

warning

As of July 2023, Universal Analytics (UA) is being phased out in favor of Google Analytics 4 (GA4). After this date, UA properties will no longer be able to process new data. They are expected to become inaccessible by the end of the year. For details on differences between property types and other operations, please refer to my article titled Universal Analytics (UA) to Google Analytics 4 (GA4). You may also request technical support via technical support.

JavaScript Error Object

During the rendering of a web page or screen, at runtime, unexpected issues often manifest as notifications visible in the console. These notifications are actually records of error objects reported at the runtime level2. While error objects are naturally used only during runtime, they can also be user-defined3. Let’s now focus on the main topic.

Web API context4, the ErrorEvent interface (interface) represents events providing information about errors occurring in scripts or files. The part we’ll focus on will be related to window and element objects.

Window: error event triggers when a resource cannot be loaded or used, and is associated with the window object. For example, if a script execution error occurs, an error record will appear within the window object.

    <script>
      let fetchData = false;
      let fetchData = true;
    </script>

As you know with the let keyword, re-declaration (reassignment) is not allowed5. In such cases, a JavaScript error occurs. Therefore, the above lines will generate an error for us. In this situation, we can catch the details of the relevant error using window.addEventListener('error', (event) => {...})67.

window error event listener
window error event listener

As shown in the above image, the error object contains many useful pieces of information. However, particularly noteworthy fields can be summarized as type, lineno, and message.

console.log(`${event.type}: ${event.message}, line: ${event.lineno}`);

Now let’s move on to the error event related to the element object.

Element: error event triggers when a resource fails to load or becomes unavailable, and is associated with the element object. For example, if a script execution error occurs, or if an image is not found or invalid, an error record is generated. The event object is an instance of UIEvent if it was created by a user interface (UI) element, otherwise it is an instance of Event8.

Broken Images
Broken Images

You may notice that some images are not loading (broken) in the example above. Now, let’s perform actions to catch these types of errors, just as they appear in the image. First, we need to define our scope. Instead of focusing on the entire page, we can also target specific areas (such as content within an element, class, or id). We’ll collect these images into an array and check them one by one.

Array.from(document.querySelectorAll('img')).forEach(img => {
  img.addEventListener('error', (err) => {
    console.log(err);
  })
});

The above snippet takes the img element and places it into an array via a query, and listens for the error event, logging the error details to the console.

Element Error
Element Error

As shown in the image, a record is created for each broken img. For now, the src value is sufficient for our purposes.

console.log(`${err.type}: ${err.target.src}`);

Let’s now summarize the topics we’ve discussed so far.

Using the JS error object, we can catch errors related to both the window and specific element, and perform actions based on the information provided. We would like to view these errors in Google Analytics, specifically as errors and the page where the error occurred. Once we’ve completed the error detection phase, we can proceed to define a Google Analytics event.

Logging Google Analytics Error Reports

Array.from(document.querySelectorAll('img')).forEach(img => {
 img.addEventListener('error', (err) => {
  gtag('event', 'error', {
   'event_category': 'Broken Image',
   'event_label': err.target.src,
   'value': 1
  });
 })
})

Yes, now our image-related errors will be reported as Google Analytics events, including the image source (src) path. From this point on, these reports can be used alongside page and user data.

Google Analytics Events
Google Analytics Events

Additionally, you can monitor the volume of visitors using ad blockers by leveraging error logs from the window object. Of course, not only ad blockers, but any blocker that prevents tracking code from functioning will also be detected.

JS Errors
JS Errors

The image above shows the error logs I’ve used and plotted into a chart using Looker Studio. These error logs are reflected in the chart as follows.

Looker Studio Error Logs
Looker Studio Error Logs

Before moving on to the other topics listed above, I’d like to add a note regarding Google Analytics.

Google Analytics: Exceptions

Google Analytics provides us with an exceptions event to track the number and types of crashes or errors occurring on a web page9.

gtag('event', 'exception', {
 'description': 'error message',
 'fatal': false   // you can set it to true if the error is critical
});  

You can view these event records through the Google Tag Assistant as shown below10.

Google Tag Assistant - Exception
Google Tag Assistant - Exception

So, how can we view exception records through Google Analytics?

Exception is actually a dimension located under the Behavior reports, just like other event records. However, it is not included in the pre-built reports. Therefore, we need to create a custom, specifically tailored report for events with the action definition set to exception. To do this, you can follow the steps under Customization > Custom Reports. The metrics we’ll use are Exceptions, Exceptions/Screen, Crashes, and Crashes/Screen.

Google Analytics Exception Report
Google Analytics Exception Report

Yes, now we can move on to the Google Tag Manager process.

Google Tag Manager and Error Events

The GTM JavaScript Error option provides us with an event trigger that activates when an error occurs11. In addition to this event, under Variables, we also have Error Line, Error Message, and Error URL variables. This allows us to send details about the error to the Google Analytics dashboard via the triggered tag121314.

GTM Error Trigger
GTM Error Trigger
GTM Error Variables
GTM Error Variables

Looker Studio and Error Visualization

Looker Studio account’s first connection to Google Analytics will make any currently active custom dimensions in Analytics directly available. However, if we wish to add error fields or other custom fields (such as events, dimensions, metrics, segments, etc.) to an existing report, we must first update the existing connected data source.

To update, follow the steps: Looker Studio > Source > Manage connected data sources, and then click the Refresh link in the row containing the Google Analytics data source we wish to use. Afterward, through the relevant View, we can select the Reconnect option to make the new fields available for use.

Looker Studio - Error Log
Looker Studio - Error Log

Yes, once the relevant metrics and dimensions are available, we can begin using them within the charts.

Footnotes

  1. Grav
  2. Error, MDN web docs
  3. Exception handling statements, MDN web docs
  4. Web API, MDN web docs
  5. JavaScript Variable Declaration Methods
  6. Window: error event, MDN web docs
  7. EventTarget.addEventListener, MDN web docs
  8. Element: error event, MDN web docs
  9. Measure exceptions, Google Analytics
  10. Check exceptions and custom dimensions and metrics, Google Analytics
  11. JavaScript error trigger, Tag Manager Help
  12. JavaScript error tracking in Google Analytics via Google Tag Manager: The unsung hero, Tatvic
  13. Track javascript errors and how to fix the errors
  14. #GTMtips: Create A Generic Event Tag, Simoahava