Error-logging for javascript on client side

If your website is using Google Analytics, you can do what I do:

window.onerror = function(message, source, lineno, colno, error) {
  if (error) message = error.stack;
  ga('send', 'event', 'window.onerror', message, navigator.userAgent);
}

A few comments on the code above:

  • For modern browsers, the full stack trace is logged.
  • For older browsers that don't capture the stack trace, the error message is logged instead. (Mostly earlier iOS version in my experience).
  • The user's browser version is also logged, so you can see which OS/browser versions are throwing which errors. That simplifies bug prioritization and testing.
  • This code works if you use Google Analytics with "analytics.js", like this. If you are using "gtag.js" instead, like this, you need to tweak the last line of the function. See here for details.

Once the code is in place, this is how you view your users' Javascript errors:

  1. In Google Analytics, click the Behavior section and then the Top Events report.
  2. You will get a list of Event Categories. Click window.onerror in the list.
  3. You will see a list of Javascript stack traces and error messages. Add a column to the report for your users' OS/browser versions by clicking the Secondary dimension button and entering Event Label in the textbox that appears.
  4. The report will look like the screenshot below.
  5. To translate the OS/browser strings to more human-readable descriptions, I copy-paste them into https://developers.whatismybrowser.com/useragents/parse/

enter image description here


Look into window.onerror. If you want to capture any errors, and report them to the server, then you could try an AJAX request, perhaps.

window.onerror = function(errorMessage, errorUrl, errorLine) {
    jQuery.ajax({
        type: 'POST',
        url: 'jserror.jsf',
        data: {
            msg: errorMessage,
            url: errorUrl,
            line: errorLine
        },
        success: function() {
            if (console && console.log) {
                console.log('JS error report successful.');
            }
        },
        error: function() {
            if (console && console.error) {
                console.error('JS error report submission failed!');
            }
        }
    });

    // Prevent firing of default error handler.
    return true;
}

Disclaimer: I'm CEO and creator of Sentry, an open source and paid service which does crash reporting for many languages, including Javascript.

It can be pretty challenging to capture frontend exceptions. Technology has gotten better (browser JS engines), but there's still a lot of limitations.

  1. You're going to need a server-side logging endpoint. This has a few complexities as it's possible to abuse it (i.e. PEN testers may try to expose vulnerabilities in it). You also need to deal with CORS here. I'd obviously recommend Sentry for this, as we're best in class, and if you want you can host the server yourself (as its open source).
  2. The implementation of actually capturing the errors in your code is pretty complicated. You cant rely on window.onerror for various reasons (mostly because browsers historically give bad information here). What we do in the raven.js client (which is based on TraceKit) is patch a number of functions to wrap them in try/catch statements. For example, window.setTimeout. With this we're able to install error handlers that will generate full stacktraces in most browsers.
  3. You'll want to ensure you're generating sourcemaps for your code, and that the server handling the data supports them. Sentry does this both by scraping them automatically (via the standards) or allowing you to upload them via an API. Without this, assuming you're minifying code, things become almost unusable.
  4. The last major issue is noise. Most browser extensions will inject directly into your scripts so you need to filter out the noise. We solve this in two ways: a blacklist of patterns to ignore (i.e. "Script error." being the most useless), as well as a whitelist of domains to accept (i.e. "example.com"). We've found the combination of the two being effective-enough at removing most random noise.

Some things you should be aware of on the server:

  • Clients will sometimes persist open (i.e. a bot, or a bad user) and cause large amounts of useless data or simple old errors.
  • Your server should be able to handle a cascade of these events and fail gracefully. Sentry does this by rate limiting things and sampling data.
  • Exceptions are localized into the browser language, and without a centralized database you will be stuck translating them yourself (though its generally obvious what they mean).