The 'onerror' event handler:
JavaScript 1.1 allowed new event handler named 'onerror'. 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:
- url (the url of the page that caused the error)
- line (the line where the error occurred).
Syntax:
onerror=handleErr
function handleErr(msg,url,l)
{
//Handle the error here
return true
}
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.
Example:
<html>
<head><title>OnError Event</title>
<script type="text/javascript">
onerror=handleErr
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"
alert(txt)
return true
}
function message()
{
allart("Hello Puru!")
}
</script>
</head>
<body bgcolor="silver">
<input type="button" value="Click Here" onclick="message()" />
</body>
</html>
Output: Output of this script is as follows:
Figure 1: Click this button.
When you click on the button the following error will raise.
Figure 2: onerror event handler through the exception.
See the line number 18 in the given example and replace by the following line.
alert("Hello Puru!")
You will see the following output:
Figure 3: Alert box display the message.