Improved javascript global handler

Revisiting an old post about adding a global javascript error handler to your website.  The reason that is valuable is because many things interfere with javascript in the browser, not least plugins that operate by injecting javascript in the webpage.

As I was recently engaged to make some javascript I thought I’d use the same method I blogged on, however I found something that irked me.  I’d used some string processing to grab the interesting parts of the error object and that processing contained an error.  It is still there, so have a look to see if you can spot it…

Subsequently I’ve improved the javascript to use a built-in function and handle the different types of error object at the server-side instead.  This is a much more robust solution as it is both more terse and robust in this form.

Below you can see this new code repeated in full so you don’t need to jump back to the old post if you don’t want to.

Step 1: Register the handler

Add a handler to the window.onerror like so:

  window.onerror = reportUnhandledJavascriptErrors;

Step 2: Write the handler

Using the built in javascript function arguments and JSON.stringify call a service:

  function reportUnhandledJavascriptErrors(){
    var jsonString = JSON.stringify(arguments);

Step 3: Call your web-service

If you’re using jQuery I’d suggest posting the data something like this:

function callService(data){
  var myServiceUrl = '';
  $.post(myServiceUrl, data);

There is the opportunity in the jQuery post method to add a handler to run on completion of the post, however in the case of a global exception you aren’t likely to know exactly where it has originated.  If you did know where the error was coming from you should write a specific error handler and probably report back to the user.

If you’re interested in the server-side handling of the global javascript exception you can read my subsequent post where I describe handling the different shape of javascript objects produced in different browsers elegantly.  Also my first post on the topic contains further information on what to expect in the error object including useful information like the stack trace.

0 comments… add one

Leave a Comment