The onerror property of a Window object is special. If you assign a function to this property, the function will be invoked whenever a JavaScript error occurs in that window: the function you assign becomes an error handler for the window.
Three arguments are passed to an error handler. The first is a message describing the error that occurred. This may be something like "missing operator in expression", "self is read-only", or "myname is not defined". The second argument is a string that contains the URL of the document containing the JavaScript code that caused the error. The third argument is the line number within the document where the error occurred. An error handler can use these arguments for any purpose it desires. A typical error handler might display the error message to the user, log it somewhere, or force the error to be ignored.
In addition to those three arguments, the return value of the onerror handler is significant. Browsers typically display an error message in a dialog box or in the status line when an error occurs. If the onerror handler returns true, it tells the system that the handler has handled the error and that no further action is necessary -- in other words, the system should not display its own error message. For example, if you do not want your users to be pestered by error messages, no matter how buggy the code you write is, you could use a line of code like this at the start of all your JavaScript programs:
self.onerror = function( ) { return true; }
Of course, doing this will make it very difficult for users to give you feedback when your programs fail silently without producing error messages.
We'll see a sample use of an onerror handler in Example 14-1. That example uses the onerror handler to display the error details to the user and allow the user to submit a bug report containing those details.
Note that the onerror error handler is buggy in Netscape 6. Although the function you specify is triggered when an error occurs, the three arguments that are passed are incorrect and unusable. Netscape 6 and other browsers that support JavaScript 1.5 have an alternative means of catching and handling errors, however: they can use the try/catch statement. (See Chapter 6 for details.)
Copyright © 2003 O'Reilly & Associates. All rights reserved.