Main Page

Extracting error information

In this example, an exception occurs when an attempt is made to call
nonExistentFunction()
,
which doesn’t exist. When this happens, the alert is displayed containing the message,
“An error
occurred.”
Unfortunately, the browser ’s error message is also displayed. To hide the error from the
browser (and thus prevent it from reporting the error), the
onerror
event handler must return a value
of
true
:
<html>
<head>
<title>OnError Example</title>
<script type=”text/javascript”>
window.onerror = function () {
alert(“An error occurred. “);
return true;
}
</script>
</head>
<body onload=”nonExistentFunction()”>
</body>
</html>
Extracting error information
Simply knowing that an error occurred is of little use to a programmer without the error details.
Fortunately, the
onerror
event handler provides three pieces of information to identify the exact
nature of the error:
?
Error message — The same message that the browser would display for the given error
?
URL — The file in which the error occurred
?
Line number — The line number in the given URL that caused the error
This information is passed as three parameters into the
onerror
event handler and can be accessed
like this:
<html>
<head>
<title>OnError Example</title>
<script type=”text/javascript”>
window.onerror = function (sMessage, sUrl, sLine) {
alert(“An error occurred:\n” + sMessage + “\nURL: “ + sUrl +
“\nLine Number: “ + sLine);
return true;
}
</script>
</head>
<body onload=”nonExistentFunction()”>
</body>
</html>
Using this code, it is possible to create custom JavaScript error dialogs that mimic the functionality of
browser-error dialogs.
420
Chapter 14
17_579088 ch14.qxd 3/28/05 11:41 AM Page 420


JavaScript EditorFree JavaScript Editor     Ajax Editor


©