JavaScript The onerror Event

The onerror Event

We have just explained how to use the try...catch statement to catch errors in a web page. Now we are going to explain how to use the onerror event for the same purpose.
The onerror event is fired whenever there is a script error in the page.
To use the onerror event, you must create a function to handle the errors. Then you call the function with the onerror event handler. The event handler is called with three arguments: msg (error message), url (the url of the page that caused the error) and line (the line where the error occurred).


function handleErr(msg,url,l)
//Handle the error here
return true or false

The value returned by onerror determines whether the browser displays a standard error message. If you return false, the browser displays the standard error message in the JavaScript console. If you return true, the browser does not display the standard error message.


The following example shows how to catch the error with the onerror event:

<script type="text/javascript">
var txt="";
function handleErr(msg,url,l)
txt="There was an error on this page.\n\n";
txt+="Error: " + msg + "\n";
txt+="URL: " + url + "\n";
txt+="Line: " + l + "\n\n";
txt+="Click OK to continue.\n\n";
return true;
function message()
adddlert("Welcome guest!");
<input type="button" value="View message" 
onclick="message()" />
JavaScript The onerror Event Reviewed by 1000sourcecodes on 06:37 Rating: 5
Powered by Blogger.