Browse DevX
Sign up for e-mail newsletters from DevX


Eliminate Irritating JavaScript Errors : Page 2

No one likes those irritating JavaScript error messages, but to eliminate them you must add client-side error handling to your scripts, or, risk losing your audience.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Generating an Exception
Listing 1 shows an HTML page containing script that is supposed to display the message "Hello World!" when you click the View Message button; however, there's a typo in the argument of the onclick event handler. The function name is misspelled. Therefore, the JavaScript engine cannot find the function, considers it missing, creates an exception and throws an error. Try it now. Figure 1 shows the results of running the HTML page in Internet Explorer. Clicking the View Message button causes an error and forces the browser to display the error message.

Although the dialog is not exactly the same, viewing the HTML page in with Netscape 6 produces a similar error message. (See Figure 2) Handling Exceptions with Try/Catch
To solve the problem, you can wrap your script inside the try and catch statements so you can take more appropriate action, such as writing the errors to a flat file or database for tracking or monitoring, (requires another round trip to the server or more advanced techniques such as the IE WebService Behavior or XMLHTTPRequest), writing a custom message to the client window with options for the user, or even redirecting to a new page.

Listing 2 contains the Hello World page rewritten to use the try and catch statements. Note that the function name appears after the try statement, which is misspelled again. JavaScript will try to invoke this function, which doesn't exist; therefore, it throws an instance of the error object. However, this time, rather than letting the script engine display the default error message, the catch block catches the error and executes some custom code to handle it. The code displays a custom error message informing the user what happened and preventing annoyance. Try it now. The custom message shown in Listing 2 displays the error number and error description for educational purposes (see Figure 3), but in real world situations I recommend not displaying these properties. They are of no use to your audience. Instead, you can use an alternate to the alert method—the confirm method—which not only displays a message, but also lets the user click an OK or a Cancel button, and returns true (for OK) or false (for Cancel). For more customized or complex error pages, the best option is to redirect users to a custom error page.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date