JavaScript OnError Event
In this JavaScript tutorial, you will learn about onerror event, how to use onerror event along with syntax and example.
Using onerror event:
The onerror event fires when a page has a script error. This onerror event occurs in JavaScript when an image or document causes an error during loading. This does not mean that it is a browser error. This event handler will only be triggered by a JavaScript error, not a browser error.
The general syntax of onerror event is as follows:
|
The onerror event is called by writing a function. This function is called by assigning to the onerror and the function written takes three arguments:
- message text
- URL
- line number of the error line
When an error occurs, the written function is invoked. The three values above are set to three variables. The function returns either true or false value using the return statement. The programmer would return the value false from the function if the programmer wants the browser to display the standard error message on the screen. If the programmer does not want to display the standard error message, then the returned value must be true from the function.
An example to understand the concept of onerror event in JavaScript:
|
The output of the program would be
Error Displayed
Error: Object expected
URL: http://URL displayed
Line: 18
Click to Proceed!!!!
In the above example program, the function display() has an error in it (the addalert is typed wrongly as addxlert). When the program reads this error, the onerror event handler fires and the function exfor( ) is called with the three parameters passed to it (the error message, the url of the page and the line number of error 18). These are displayed in the function which produced the output above.