window.onerror
Hate errors.
HTML
<html>
<head>
</head>
<body>
</body>
JavaScript
window.onerror = createSyncedErrorHandler('http://fiddle.jshell.net/echo/json/');
// Very simple error handler. Prints errors into the console, via console.error
// (Yes it is duplicate, but demonstration is still valid)
//
// example:
// ReferenceError: Can't find variable: foo ["http://.../bar.js", 1]
function errorHandler(message, url, line) {
console.error(message, [url, line]);
return true;
}
// A bit more sophisticated error handler, post error details to the server using XHR. This
// function is provided as factory form to wrap error's end-point
//
// usage:
// window.onerror = createSyncedErrorHandler('http://hon.gy/e/log');
function createSyncedErrorHandler (destination) {
return function (message, url, line) {
var request = new XMLHttpRequest(),
data = { message: message, source: url, line: line };
request.open("POST", destination);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.send(JSON.stringify(data));
return true;
};
}
// TODO:
// - batch upload (i.e., throttle XHR)
// - localStorage <> server sync in background
// - socket.io
// - prettified error UI
// - mixin!
// Force an error
davidhong;