Skip to content

Instantly share code, notes, and snippets.

@kris-ellery
Last active November 18, 2021 19:00
Show Gist options
  • Star 33 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save kris-ellery/10287367 to your computer and use it in GitHub Desktop.
Save kris-ellery/10287367 to your computer and use it in GitHub Desktop.
Track JavaScript errors using Universal Analytics from Google.
/**
* Track JS error details in Universal Analytics
*/
function trackJavaScriptError(e) {
var errMsg = e.message;
var errSrc = e.filename + ': ' + e.lineno;
ga('send', 'event', 'JavaScript Error', errMsg, errSrc, { 'nonInteraction': 1 });
}
window.addEventListener('error', trackJavaScriptError, false);
@szrenwei
Copy link

for compatibility( IE9 and blow), the code should be this:


function trackJavaScriptError(e) {
        var ie = window.event,
            errMsg = e.message || ie.errorMessage;
        var errSrc = (e.filename || ie.errorUrl) + ': ' + (e.lineno || ie.errorLine);
        ga('send', 'event', 'JavaScript Error', errMsg, errSrc, { 'nonInteraction': 1 });
}

@christianhaller
Copy link

If an error comes from a different domain, you don't have e.filename. So your script is accessing ie.filename. If you have a firefox, it's crashing, because ie is not defined. I changed the second line of your script. Now it's working correctly with errors from different domains.

function trackJavaScriptError(e) {
        var ie = window.event || {},
            errMsg = e.message || ie.errorMessage;
        var errSrc = (e.filename || ie.errorUrl) + ': ' + (e.lineno || ie.errorLine);
        ga('send', 'event', 'JavaScript Error', errMsg, errSrc, { 'nonInteraction': 1 });
}

@kdzwinel
Copy link

kdzwinel commented Jul 7, 2016

Universal Analytics have exception tracking support: https://developers.google.com/analytics/devguides/collection/analyticsjs/exceptions

So the code should look like this:

function trackJavaScriptError(e) {
        var ie = window.event || {},
            errMsg = e.message || ie.errorMessage;
        var errSrc = (e.filename || ie.errorUrl) + ': ' + (e.lineno || ie.errorLine);
        ga('send', 'exception', {
            'exDescription': errSrc + ': ' + errMsg,
            'exFatal': false
        });
}

@judearasu
Copy link

@kdzwinel i tried your code but its not working for me. what i noticed its not able to grab the error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment