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:
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:
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.
Leave a Reply