window.onerror

The web is a fragile thing that brakes for million reasons especially in the era of the smart phones and tables. One way to be aware of your web page’s misbehavior is to log any JavaScript errors and send them for post-mortem analysis. Meet window.onerror - an error handling callback that will be invoked for every JavaScript error appearing on your page.

window.onerror = function(message, scriptUrl, line, column) {
  // if an error occurred in our source code
  // send it to the server
  // may be send also location.href and navigator.userAgent
}

This is the basic implementation which will fix the client-side error report for you. On the server-side you can aggregate the errors and send them for analysis once a day or anything else that suits you.

To filter out error reports caused by browser plugins it is useful to check that the scriptUrl origin is the same as your web page and that the url contains “.js”. Otherwise you will be overwhelmed with crash reports caused by failing plugins (especially in IE).

The latest [html5 Web API specification]((http://www.w3.org/html/wg/drafts/html/master/webappapis.html) for the error handler has one extra parameters - error object, but it seems like only Chrome is supporting it at this moment. The classic signature of the handler uses only message, scriptUrl and line, so be no surprised if the column is undefined in older browsers. Also you can silence the error report in the script console in your browser if you return true from the onerror handler, but I would not recommend it unless you somehow manage to fix the error.

Here is a simple implementation:

window.onerror = function(message, scriptUrl, line, column) {
  if (scriptUrl.indexOf('http://your-domain.com') === 0 
    && scriptUrl.indexOf('.js') > -1) {
    
    ajaxPost('/js-error-end-point',
      {
        location: location.href,
        useragent: navigator.userAgent,
        message: message,
        scriptUrl: scriptUrl,
        line: line,
        column: column
      }
    );
  }
};

Published: October 27 2013

blog comments powered by Disqus