freshsauce web development

Logging browser javascript errors back to your server

It’s impossible to know if your web app is throwing errors in old or modern browsers unless you instrument to track those errors. The good news is it only takes a few lines of javascript code and server side code to get a proof of concept up and running.

The basic premise is in javascript register a global error handler which has no dependancies on third party libs (jQuery etc..) and on error post the information back to your server, where you can log to your favourite tool such as papertrail or loggly via monolog.

So here’s the Javascript which POST’s the error info to the URL /jsError.php in this case.

window.MaximumErrorCount = 5; // Limit number of errors sent

// register error handler
window.onerror = function(errorMsg, file, lineNumber) {
  window.errorCount || (window.errorCount = 0);

  if (window.errorCount <= window.MaximumErrorCount) {
    var request = new XMLHttpRequest(); // OK for IE8+
    request.open('POST', '/jsError.php', true); // POST to URL
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    request.send({
      errorMessage: errorMsg,
      file: file,
      url: window.location.href,
      lineNumber: lineNumber,
      ua: navigator.userAgent
    });
  }
}

Then a very basic /jsError.php implementation can log like the following

<?php
// Do something more robust in production
// to check it's a valid post etc
// also use Monolog or similar to log, but hey this is an example :)
$logMessage = sprintf(
  'JS_ERROR[%s] URL[%s] on file[%s:%s] UA[%s]',
  $_POST['errorMessage'],
  $_POST['url'],
  $_POST['file'],
  $_POST['lineNumber'],
  $_POST['ua']
);
error_log($logMessage);