Von Protonet Team. Veröffentlicht 31. August 2011.
It’s very common for back-end developers to implement a mechanism in production mode that tracks and aggregates exceptions.
But what about your front-end code? How do you know when something on your website is seriously broken and you don’t see it since it only happens in a certain browser version, that you (or your QA department) isn’t testing on?
JavaScript has defacto become one of the most popular programming languages on the web. Nowadays websites like Facebook, Twitter or GMail have a significant part of their application logic in their front-end.
An important difference between your client side JavaScript and your server side language is, that your JavaScript is executed on thousands of different machines under different circumstances (different user agents, different OS, plugins, firewall, different internet connections, …) while your server side language runs in a stable environment that is under your control.
With this blog post I’d like to show you a couple of ways how to implement a simple JavaScript exception notifier:
This is probably the easiest way especially if you are already using Google Analytics in your app.
window.onerror = function(message, file, lineNumber) {
_gaq.push([
'_trackEvent',
'error',
file + ':' + lineNumber,
message + ''
]);
};
This option makes only sense if you are running a small to medium sized website. Keep in mind that Google Analytics wasn’t designed to handle exceptions. Also if you are running a rather large website, don’t piss off your marketing department by pushing your nerdy exceptions into their tool.
Instead consider implementing option #2 or #3.
This option is also rather tailored for low-traffic websites. Additionally you need some experience in inspecting Apache log files.
window.onerror = function(message, file, lineNumber) {
new Image().src = "/this_url_doesnt_exist?message="
+ encodeURIComponent(message)
+ "&file=" + encodeURIComponent(file)
+ "&lineNumber=" + encodeURIComponent(lineNumber);
};
Now each JavaScript error will generate a new log entry in your Apache’s error.log including all relevant error information (date, user agent, error message, file, …).
This is what we use at protonet for collecting exceptions on the server side as well as on the client side.
Airbrake (formerly known as ‘Hoptoad’) is an app that takes your exceptions (regardless which programming language) and aggregates them for you.
It’s very handy for teams since you can mark exceptions as resolved and if you register a paid account you can integrate it with GitHub or lighthouseapp.
If you want to send your JavaScript exceptions to Airbrake do the following: