Reputation: 7215
I am struggling to get the GTM JS error trigger to fire for uncaught exceptions in my Angular application.
I have followed a guide here https://www.simoahava.com/gtm-tips/track-javascript-errors-events/ and have set up the trigger and tag exactly as they mention.
I am throwing an uncaught exception to try and test this out, hoping to see the error event appear in the realtime view in my GA console.
I am not seeing anything being pushed into the dataLayer when the error is thrown
I have other tags\triggers, such as a custom pageview
event which is firing perfectly fine and flowing through to GA with no problem.
Can anyone suggest what I could be doing wrong here please?
Upvotes: 4
Views: 3115
Reputation: 4602
Javascript error
trigger does not fire because angular
has a default error handling mechanism which does not let the error to be propagated outside. It consumes the error and then logs it on the console. To verify, try putting below script in your index.html file -
<script>
window.onerror = function (msg, url, lineNo, columnNo, error) {
console.log('This wont get to console because Angular!! ');
return true;
}
</script>
If you read this google help page about javascript error trigger, it says, the tag is fired on window.onError
event which never occurs because of angular's default error handler -
Google Tag Manager's JavaScript error trigger is used to fire tags when an uncaught JavaScript exception (window.onError) occurs.
You have two options to fix this -
Option 1:
Create your custom handler and manually fire the trigger by adding the error to dataLayer
. But you may need to figure out properties like gtm.errorLineNumber
and gtm.errorUrl
yourself. Checkout this working sample on StackBlitz (you'll need to change the script in index.html to point to your GTM preview/debug ) -
declare var dataLayer;
@Injectable()
export class ErrorsHandler implements ErrorHandler {
constructor(private injector: Injector) { }
handleError(error: any) {
const location = this.injector.get(LocationStrategy);
const message = error.message ? error.message : error.toString();
const url = location instanceof PathLocationStrategy
? location.path() : '';
const event = {
'event': "gtm.pageError",
'gtm.errorLineNumber': '',
'gtm.errorMessage': message,
'gtm.errorUrl': url,
'gtm.uniqueEventId': dataLayer.length+1
}
dataLayer.push(event);
}
}
Option 2:
Rethrow the error from your custom error handler, but this will break your application (also maybe infinite recursion?) -
@Injectable()
export class ErrorsHandler implements ErrorHandler {
constructor(private injector: Injector) { }
handleError(error: any) {
throw error;
}
}
Upvotes: 1