Client-Side JavaScript Error Logging, Part I

By Karolis Dzeja, UX Developer

Originally posted on my blog:

This is the first part of a series of articles describing the best practices to log client-side JavaScript errors.

Let’s run down our list of requirements:

  • We want to have the capability to log all errors.
  • We don’t want to effect the page load time for the visitor.
  • We want to be able to respond to errors as fast as possible.
  • We want to be able to choose which information to log.

How can we tell if an error occurred? JavaScript has an window.onerror event handler. Here’s an example of how it could be used:

window.onerror = function(message, url, linenumber) {
  sendErrorToServer({message: message, line: linenumber, url: url});

Every time a runtime error occurs, we can get the error message, url of the file, and line number. What’s sendErrorToServer though? Do we need a server? We’ll talk about that in the next part. Chances are you already have Google Analytics installed and, without needing to setup a server, we can send events to Google Analytics like this:

<!DOCTYPE html>
      var _gaq = _gaq || [];
      window.onerror = function(message, url, linenumber) {
        _gaq.push(['_trackEvent','Error',message, url, linenumber]);
<!-- rest of page -->

The way Google Analytics works is that it creates an array _gaq and it can start collecting commands immediately while the ga.js script loads asynchronously. Then the script looks through the array, executes the queued commands, and redefines the push function of _gaq to immediately execute commands as they are added. We want to put our script at the very top of the <head> and if we do, _gaq wouldn’t yet be defined by the snippet we copied from Google, so that’s why we make sure to define it.

This is a great start but things aren’t quite perfect yet. Looking at the list of requirements at the top: we’re not effecting the page load for the visitor, they don’t have to download anything extra, and by putting our script at the top of the <head> before any other scripts, we’re able to log errors from all scripts that load afterwards. But events don’t always show up immediately in Google Analytics. We’re limited to four fields for our data. And as per Google’s privacy policy, we can’t track any personality identifiable information about our visitors.

If we’re asking a client to implement this on their website, they’ll have the same visibility into errors as we do. Also, we can’t limit or filter the error logging without modifying this script and asking the client to update it again.

Stay tuned to find out how we can solve all of these issues…

Explode Online Sales with Automation Strategies

Learn new hacks to grow conversions and maximize customer loyalty within our new eCommerce Automation Strategy Brief (PDF).

Recent Posts