Logging client-side JavaScript errors

JavaScript interaction is not usually an option for most modern websites (try accessing some of your favorite sites with JavaScript disabled). Given the matrix of browsers, devices, software versions and extensions, exhaustive testing can be challenging.

Capturing and logging JavaScript errors that occur on the client can be just as important as inspecting application and server logs.

The following example assumes you have access to jQuery, and adds an error event handler to the current window. In the case of an error event, we dispatch a POST request with the pertinent details.

(function() {

    var logError = function( e )
    {
        if (window.jQuery)
        {
            var data = {
                f : e.filename,
                l : e.lineno,
                m : e.message
            };
            $.post('/log/error', data);
        }
    };

    if (window.addEventListener)
    {
        window.addEventListener('error', logError, false);
    }
    else
    {
        window.attachEvent('onerror', logError);
    }

})();

Depending on your application, additional information about the error can be logged server-side: referring URL, user agent, timestamp and possibly session information. Capturing these errors should give you better insight into where visitors may be experiencing an issue.