Instantly share code, notes, and snippets.

Embed
What would you like to do?
global js error handling via "window.onerror"
<script type="text/javascript">
var one_error_reported_via_onerror = false;
window.onerror = function(msg, url, line, col, error) {
if (one_error_reported_via_onerror === true) {
return false;
}
var string_tmp = msg.toLowerCase();
var substring_tmp = "script error";
if (string_tmp.indexOf(substring_tmp) > -1){
// https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onerror
//
//alert("Script Error: See Browser Console for Detail");
} else {
one_error_reported_via_onerror = true;
var message_msg = msg;
var message_url = url ? url : "";
var message_line = line ? line : "";
var message_col = col ? col : (window.event && window.event.errorCharacter ? window.event.errorCharacter : "");
var message_userAgent = navigator && navigator.userAgent ? navigator.userAgent : "";
// fallback for e.g.: IE
if (
!error
&&
typeof Error === "function"
) {
error = new Error();
}
// get information about the error e.g. "stack trace" ... (only for new browsers)
var message_error = "";
if (error) {
message_error = error;
if (JSON && typeof JSON.stringify === "function") {
message_error = JSON.stringify(error);
}
}
// Something like a "stack trace" for old browsers ...
var error_stack_string = "no stack info";
if (typeof error.stack !== "undefined") {
// e.g.: Opera 11, FF, ...
error_stack_string = error.stack;
} else if (typeof error.stacktrace !== "undefined") {
// e.g.: Opera 10
error_stack_string = error.stacktrace;
} else if (typeof error.trace === "function") {
// e.g.: IE 11
error_stack_string = error.trace();
} else if (typeof error.message !== "undefined") {
// e.g.: Opera 9
error_stack_string = error.message;
} else if (
typeof arguments === "object"
&&
typeof arguments.callee.caller === "function"
) {
// e.g. IE <= 8 (using arguments.callee.caller is deprecated - not working in strict mode in any browser!)
error_stack_string = arguments.callee.caller.toString();
}
// Report this error via ajax so you can keep track of what pages have JS issues.
jQuery.ajax({
type: "POST",
url: "/error_js.php",
data: {
msg: message_msg,
url: message_url,
line: message_line,
col: message_col,
error: message_error,
stack: error_stack_string,
browser: message_userAgent,
code: $("html").html()
},
success: function() {
if (console && console.log) {
console.log("JS error report successful.");
}
},
error: function() {
if (console && console.error) {
console.error("JS error report submission failed!");
}
}
});
}
//noinspection UnnecessaryLocalVariableJS,JSUnusedLocalSymbols
var suppressErrorAlert = false;
// If you return true, then error alerts (like in older versions of
// Internet Explorer) will be suppressed.
return suppressErrorAlert;
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment