Reputation: 14791
I am adding a global JavaScript error listening following this link, https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror. I tried to test if the code is working by producing an error. But it is not working.
This is my code
var num = {
}
num.id.toString();
window.onerror = function(message, source, lineno, colno, error) {
alert('Error');
return false;
}
As you can see in my code above, it should alert message, 'Error' because id property of test object is undefined and so that calling toString()
method on it will throw an error. But when I checked the console, I got the error. But the global error listener is not catching the error and triggered. How can I correctly set up the JavaScript global error listener?
Upvotes: 2
Views: 436
Reputation: 3431
Wrong order - you are trying to bind the event handler after an error that stops script execution. Turn that around:
window.onerror = function(message, source, lineno, colno, error) {
alert('Error');
return false;
}
var num = {
}
num.id.toString();
Upvotes: 4