Created
November 29, 2012 21:52
-
-
Save JamesMGreene/4172161 to your computer and use it in GitHub Desktop.
jQuery event handlers to prevent logging after the window goes crazy! =)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is pretty brilliant...love the online/offline handling!
Out of curiosity, why
JSON.stringify(err)
rather than passerr
directly?