JavaScript The onerror Event
Using the onerror event is the old standard solution to catch errors in a web page.
Examples
The onerror event
(an example with an error)
How to use the onerror event to catch errors in a web page.
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).
Syntax
onerror=handleErr
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.
Example
The following example shows how to catch the error with the onerror event:
<html>
<head>
<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()
{
adddlert("Welcome guest!");
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>
|
|
|
|
See why there are 20,000+ Ektron integrations worldwide.
Request an INSTANT DEMO or download a FREE TRIAL today. |
|
|
|