Debugging and monitoring GTM Variables for errors

Google Tag Manager does not throw any error when the code in a variable fails. This is not bad per se as it would save us from having our sites failing if something is not coded as it should, but it will blind us agains some minor errors that may not be noticiables, for example if our Enhanced Ecommerce is failing for a certain product, or from some specific browser.

Thanksfully we can use try{}catch(e){} to capture those errors :). And we could use it to send an event to GA so we can monitor and fix the errors easily, having also all the info about where did the error happened, which browsers, location, etc.

The main problem of sending an event within a variable error is that we may end having dozens of duplicated events for each error as variables got executed several times and not just once . The following piece of code will loop thru all the dataLayer pushes to find out if the current error has been already pushed to avoid this problem.

try {
    // JS Variable Code Goes Here
} catch (e) {
    if (window.dataLayer.filter(function(obj) {
            return obj.errorMsg === e.message;
        }).length == 0) {
        window.dataLayer.push({
            'event': 'variable error',
            'errorMsg': e.message
        });
    }
}

Now just set an event that fires on the custom event named “variable error”, and that reads errorMsg variable value from the dataLayer.
You can easily personalize this to your needs.

Let’s see an small report for an Enhanced Ecommerce Implementation that is using Variables instead of the dataLayer values to populate the info:

debug_gtm_var_01



Those errors won’t prevent the hit to be sent, but ecommerce data will be missing on them.

But this is not where it ends, now you can use Real Time reporting to monitor your recently published container and be able to fix things in almost no time:

debug_gtm_var_02

Update Dec-2018:  Thanks Timur for letting me know that now GTM is declaring the dataLayer variable locally. Added window. scope naming to the snippet. 

Comments

2 responses to “Debugging and monitoring GTM Variables for errors”

  1. Grant kemp Avatar

    Where do you put that snippet of code ?

    Do you add it as custom html to load last ?

  2. Yoray Avatar

    David,
    This is very high quality stuff.
    Thank you for sharing this knowledge with us.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.