1
\$\begingroup\$

Apart from general JavaScript knowledge, this snippets requires someone who knows how to properly use Google Analytics API.

To log errors on my site, I use this code:

try {
  window.addEventListener("error", function(e) {
    var file = e.filename.substr(e.filename.lastIndexOf("/")+1);
    // for some reason, filename sometimes contained path, sometimes just name
    if(file.length==0)
      file = e.filename;
    var msg = file+":"+e.lineno+":"+e.colno+" \""+e.message+"\" Browser: "+navigator.userAgent;

    if(typeof ga=="function") {
      ga('send', 'event', 'jserror', 'click', msg, {'transport': 'beacon'});
    }
    else {
      // This is executed when google analytic is not loaded
      // which happens in debug mode
      console.error(msg);
    }
  });
}
catch(e) {
  console.warn("Failed to add error callback.");
}

I'm especially interested to know whether I'm using the google analytics API correctly. Maybe I could log the data about error in multiple columns?

I'm new to google analytics so feedback is very valuable for me.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$
ga('send', 'event', 'jserror', 'click', msg, {'transport': 'beacon'});

Yup, that's how I would do events in Google Analytics. However, the API also provides a special call for errors. It's found under Exception Tracking.

ga('send', 'exception', {
  'exDescription': msg,
  'exFatal': false
});

Another is that you're wrapping an addEventListener call into a try-catch. Not sure why this is required. The callback is fired asynchronously, thus the try-catch will make no sense (unless somehow, window or addEventListener doesn't exist)

if(typeof ga=="function") {

The snippet (and not the script that it loads) creates the global ga function for you, which means the global ga should be present when the snippet is present. It's seen in the snippet as this portion:

i[r]=i[r]||function(){...}

But I see that it's possible that you're not loading it when debugging. So this can be ignored I suppose.

Lastly, rename e to error. This makes the variable tell what it is more.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.