Skip to content

Instantly share code, notes, and snippets.

@JamesMGreene
Created November 29, 2012 21:52
Show Gist options
  • Select an option

  • Save JamesMGreene/4172161 to your computer and use it in GitHub Desktop.

Select an option

Save JamesMGreene/4172161 to your computer and use it in GitHub Desktop.
jQuery event handlers to prevent logging after the window goes crazy! =)
(function($, window, undefined) {
// WARNING! Set this as you see fit
var suppressUnhandledErrors = true;
var okToLogErrors = true;
var isOnline = true;
var offlineErrorQueue = [];
var logError = function(err) {
if (!okToLogErrors) {
return;
}
if (!isOnline) {
offlineErrorQueue.push(err);
return;
}
// Fire and forget
$.ajax({
type: 'POST',
url: '/errors',
dataType: 'application/json',
data: JSON.stringify(err)
});
};
// Handle unhandled JavaScript errors
window.onerror = function(errorMsg, url, lineNum, columnNum) {
var err = new Error(errorMsg);
err.name = "UnhandledError";
err.fileName = url || window.location.href;
err.lineNumber = lineNum || 0;
err.columnNumber = columnNum || 0;
err.stack = null;
logError(err);
// Let the browser keep trying to execute JavaScript by suppressing ("handling") the error?
return suppressUnhandledErrors;
};
var $win = $(window);
$.each(['abort', 'cancel', 'stalled', 'suspended', 'unload'], function(i, e) {
$win.on(e, function() {
okToLogErrors = false;
});
});
$(window.document).on('error', function(err) {
err.fileName = err.fileName || window.location.href;
err.lineNumber = err.lineNumber || 0;
err.columnNumber = err.columnNumber || 0;
err.stack = err.stack || null;
logError(err);
});
$win.on('offline', function() {
isOnline = false;
});
$win.on('online', function() {
isOnline = true;
$.each(offlineErrorQueue, function(i, e) {
logError(e);
});
offlineErrorQueue.length = 0;
});
})(jQuery, this);
@JamesMGreene

Copy link
Copy Markdown
Author

If you want to get really "crazy" cough AWESOME cough, you could also take it one step further by overriding jQuery's on method to essentially add a try-catch construct internally, a la http://forum.jquery.com/topic/catching-all-errors

@JamesMGreene

Copy link
Copy Markdown
Author

Oh, and you may also find the addition of a library like StackTrace.js to be useful (despite its currently terrible API 😢).

@dahlbyk

dahlbyk commented Nov 30, 2012

Copy link
Copy Markdown

This is pretty brilliant...love the online/offline handling!

Out of curiosity, why JSON.stringify(err) rather than pass err directly?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment