Logging Clientside JavaScript Errors on Server

I have just implemented server side error logging on javascript errors on a project at work. There is a mixture of legacy code and new code using jQuery.

I use a combination of window.onerror and wrapping the jQuery event handlers and onready function with an error handling function (see: JavaScript Error Tracking: Why window.onerror Is Not Enough).

  • window.onerror: catches all errrors in IE (and most errors in Firefox), but does nothing in Safari and Opera.
  • jQuery event handlers: catches jQuery event errors in all browsers.
  • jQuery ready function: catches initialisation errors in all browsers.

Once I have caught the error, I add some extra properties to it (url, browser, etc) and then post it back to the server using an ajax call.

On the server I have a small page which just takes the posted arguments and outputs them to our normal server logging framework.

I would like to open source the code for this (as a jQuery plugin). If anyone is interested let me know, it would help to convince the bosses!


Short answer: Yes, it is possible.

Longer answer: People have already written about how you can (at least partially) solve this issue by writing your own code. However, do note that there are services out there that seems to have made sure the JS code needed works in many browsers. I've found the following:

  • http://trackjs.com
  • https://www.atatus.com
  • http://jserrlog.appspot.com
  • http://muscula.com
  • https://sentry.io
  • https://rollbar.com
  • https://catchjs.com

I can't speak for any of these services as I haven't tried them yet.


You could try setting up your own handler for the onerror event and use XMLHttpRequest to tell the server what went wrong, however since it's not part of any specification, support is somewhat flaky.

Here's an example from Using XMLHttpRequest to log JavaScript errors:

window.onerror = function(msg, url, line)
{
  var req = new XMLHttpRequest();
  var params = "msg=" + encodeURIComponent(msg) + '&url=' + encodeURIComponent(url) + "&line=" + line;
  req.open("POST", "/scripts/logerror.php");
  req.send(params);
};