I would like to catch every undefined function error thrown. Is there a global error handling facility in JavaScript? The use case is catching function calls from flash that
Assign the window.onerror
event to an event handler like:
As commented in the code, if the return value of window.onerror
is true
then the browser should suppress showing an alert dialog.
In a nutshell, the event is raised when either 1.) there is an uncaught exception or 2.) a compile time error occurs.
uncaught exceptions
- throw "some messages"
- call_something_undefined();
- cross_origin_iframe.contentWindow.document;, a security exception
compile error
setTimeout("{", 10);
, it will attempt to compile the first argument as a script
Example of the onerror code above in action after adding this to a test page:
var error_data = {
url: document.location.href,
};
if(error != null) {
error_data['name'] = error.name; // e.g. ReferenceError
error_data['message'] = error.line;
error_data['stack'] = error.stack;
} else {
error_data['msg'] = msg;
error_data['filename'] = filename;
error_data['line'] = line;
error_data['col'] = col;
}
var xhr = new XMLHttpRequest();
xhr.open('POST', '/ajax/log_javascript_error');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('JS error logged');
} else if (xhr.status !== 200) {
console.error('Failed to log JS error.');
console.error(xhr);
console.error(xhr.status);
console.error(xhr.responseText);
}
};
xhr.send(JSON.stringify(error_data));
https://jsfiddle.net/nzfvm44d/