As explained in Exception Handling (December 9, 1999), you want to avoid system messages because they don't make much sense for the average user. An alternative to adding the try...catch blocks is to redefine the window's onerror property:
window.onerror = myError;
You then define the myError function as you wish. For example:
function myError(message, url, line){
alert("Let me handle it all by myself");
return true;
}
The error handling function has three parameters: message that describes the error, url that holds the URL of the file, and line which points to the culprit line in the file. Your handling of the error may or may not use these parameters. In the example above, we just print a message, avoiding these parameters altogether.
The tricky part is whether the system does or does not show its error in addition to your treatment. You can control it by returning either a true or a false value. When the error function returns a true value, the system will not display any alert boxes of its own. When the function returns a false value, the system will display its original error messages after it exits the error handling function.
The following script shows the false-returning version. Try it:
<HTML>
<HEAD>
<TITLE> onerror Example 2 </TITLE>
<SCRIPT LANGUAGE="JavaScript">
window.onerror = myError;
function myError(message, url, line){
alert("Let me handle it first...");
return false;
}
</SCRIPT>
</HEAD>
<BODY>
<IMG SRC="photo32.gif">
<SCRIPT LANGUAGE="JavaScript1.2">
<!--
for (image=0; image < document.images.length + 2; image++) {
alert("The width of image " + image + " is " + document.images[image].width);
}
// -->
</SCRIPT>
</BODY>
</HTML>
Here is the true-returning version. Try it:
<HTML>
<HEAD>
<TITLE> onerror Example 1</TITLE>
<SCRIPT LANGUAGE="JavaScript">
window.onerror = myError;
function myError(message, url, line){
alert("Let me handle it all by myself");
return true;
}
</SCRIPT>
</HEAD>
<BODY>
<IMG SRC="photo32.gif">
<SCRIPT LANGUAGE="JavaScript1.2">
<!--
for (image=0; image < document.images.length + 2; image++) {
alert("The width of image " + image + " is " + document.images[image].width);
}
// -->
</SCRIPT>
</BODY>
</HTML>
The exception shown above is triggered by accessing a non-existent image. You can learn more about exception handling in Exception Handling (December 9, 1999) and in Column 38, Exception Handling.
People who read this tip also read these tips:
Look for similar tips by subject:
|