Skip to content

Instantly share code, notes, and snippets.

@westonganger
Last active September 29, 2021 17:45
Show Gist options
  • Save westonganger/20a6e45b840e3c54c613740b42f31eaa to your computer and use it in GitHub Desktop.
Save westonganger/20a6e45b840e3c54c613740b42f31eaa to your computer and use it in GitHub Desktop.
Javascript Error Handler
// Links
// https://stackoverflow.com/questions/951791/javascript-global-event-mechanism
// https://stackoverflow.com/a/49560222/3068360
// https://stackoverflow.com/questions/5328154/catch-all-javascript-errors-and-send-them-to-server
window.addEventListener('error', function(event) {
// Instead of window.onerror we use addEventListener with capture option set to true to get the most errors
// window.onerror = function(message, file, line, col, error){
// https://stackoverflow.com/q/54209739/3068360
// https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror
// event is type of https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent
$.ajax({
url: '/path/to/handle_js_exception',
dataType: 'json',
data: {
name: event.error.name,
message: event.message,
url: document.location.href,
user_agent: navigator.userAgent,
stacktrace: (event.error && event.error.stack), // stacktrace contains info about file, line, and col so no need to send those
}
}).done(function(){
//console.log("Successfully sent error");
});
// No need to log error details as console will catch it automatically
//console.log('error');
}, true); // use true for capture option so that all errors are caught
window.addEventListener('unhandledrejection', function(e){
// https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event
$.ajax({
url: '/path/to/handle_js_exception',
dataType: 'json',
data: {
name: "Unhandled Promise Rejection (unhandledrejection)",
message: e.reason,
url: document.location.href,
user_agent: navigator.userAgent,
}
}).done(function(){
//console.log("Successfully sent error");
});
// No need to log error details as console will catch it automatically
//console.log('unhandledrejection');
}, true); // use true for capture option so that all errors are caught
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment