Using window.onerror How to Catch Unhandled Errors in Javascript

Client side scripting language Javascript has an event driven error handling model where you define a handler function for window.onerror to override the error handling.

This method has three arguments error message, url and line number. It should return true if the error is handled and return false to let the browser handle the error.

 

window.onerror = function(errmsg, url, line) {

alert(“unhandled Error occured : ” + errmsg + “\n\n On Link: ” + url + “\nat Line Number #: ” + line);
// doSomethingToLogErrorDeatils
var jsSuppressError = true;
return jsSuppressError;
};



or you can also set Nothing to be happen when error occurs.


function noErrorMessages () { return true; }
window.onerror = noErrorMessages;

If you set jsSuppressError as return true, then error alerts (in IE, FF) will be suppressed. and In Chrome, returning ‘true’ from window.onerror allows the error to propagate, and returning ‘false’ suppresses it.

 



Here is the example you can run in your local machine to check the output.

 

<head>
<script type="text/javascript">
window.onerror = function(errmsg, url, line) {
alert("unhandled Error occured : " + errmsg + "\n\n On Link: " + url + "\nat Line
Number #: " + line);
// doSomethingToLogErrorDeatils
var jsSuppressError = true;
return jsSuppressError;
};
</script>

<script type="text/javascript">
document.write('This code is taken from http://javadotnet.in. this will create unhandled exception
</script>
</head>

3 Responses to Using window.onerror How to Catch Unhandled Errors in Javascript

  1. todovalencia says:

    My spouse and I absolutely love your blog and find a
    lot of your post’s to be exactly what I’m looking for. Does one offer guest writers to write content for you?
    I wouldn’t mind composing a post or elaborating on many of the subjects you write concerning here. Again, awesome blog!

  2. Pearlene says:

    Hello there! This article could not be written any better!
    Looking through this article reminds me of my previous roommate!
    He continually kept talking about this. I’ll send this article
    to him. Pretty sure he will have a great read.

    Thanks for sharing!

Leave a Reply

Your email address will not be published.