Team LiB
Previous Section Next Section

Exploiting the OnError() Method

One event handler that was not discussed in Chapter 6 is the OnError() event handler. The OnError() event handler can act like a global try-catch block for your entire Web page, and will capture any error that occurs. Here is a simple example to demonstrate:

<html> 
  <head> 
    <title>
      JavaScript Professional Projects - The OnError Method 
    </title>

    <script language="JavaScript"> 
    <!--
      function error() 
      { 
        alert( "An error occured." ); 
      }
      window.onerror = error; 
    // -->
    </script> 
  </head>

  <body>

    <center>
      <font size=6>JavaScript Professional Projects</font><br> 
      <font size=4> Chapter 13: The OnError Method</font>
</center>

    <br><br> 
    <br><br>

    This page contains a JavaScript error  
    which is caught by the OnError event handler.

    <script language="JavaScript"> 
    <!--
      document.write( myObject.toString() ); 
    // -->
    </script>

  </body> 
</html>

This example captures all errors that occur in the page with the OnError event handler of the window object. This example uses an alert dialog to tell the user that an error occurred, but as I said before, telling the user about errors is generally not a good idea. The fact that errors are annoying, compounded with the fact that alert dialog boxes are also annoying, might make the visitor never want to visit your site again. If you had not expected the error to occur at all, it is usually a better idea to simply ignore it than bombarding the visitor with alert dialogs.

The OnError() event handler is also useful if you're worried about only one portion of your code causing errors. You can place the event handler

OnError="JavaScript: null;"

in a surrounding tag and it would block all errors that occur therein.


Team LiB
Previous Section Next Section