I\'m looking to start making my JavaScript a bit more error proof, and I\'m finding plenty of documentation on using try
, catch
, finally
,
Nicholas Zakas of Yahoo! fame did a talk on Enterprise Error Handling (slides) at Ajax Experience 2008, in which he proposed something like this:
function log(sev,msg) {
var img = new Image();
img.src = "log.php?sev=" +
encodeURIComponent(sev) +
"&msg=" + encodeURIComponent(msg);
}
// usage
log(1, "Something bad happened.")
// Auto-log uncaught JS errors
window.onerror = function(msg, url, line) {
log(1, msg);
return true;
}
A year later, Nicholas Zakas posted an update on his blog which included a clever pattern to inject error handling code automatically on your production environment (using aspect-oriented programming).
When you start logging window.error calls, you're going to notice two things:
Reducing the torrent of log entries is as simple as testing for severity and/or a random number before logging to the server:
function log(sev,msg) {
if (Math.random() > 0.1) return; // only log some errors
var img = new Image();
img.src = "log.php?sev=" +
encodeURIComponent(sev) +
"&msg=" + encodeURIComponent(msg);
}
Handling the useless window.error in undefined:0
errors depends on your site architecture, but can try identifying all Ajax calls and throwing an exception when something fails (possibly returning a stack trace using stacktrace.js).