Eliminate Irritating JavaScript Errors

Eliminate Irritating JavaScript Errors

ou come home, turn on the computer, pull up a Web site, click on a link and HALT! A JavaScript alert box pops up; telling you there is a runtime error, and asking, “Do you wish to debug?” Well that message is fine for developers, but what about the end-users?your audience? The truth is the audience expects the Internet to be quick, easy and free. When they see errors, they mostly don’t know what to do, so they take the path of least resistance?by closing the Alert box and clicking a different link or, worse, leaving your site altogether.

To avoid this problem, you need to learn how to avoid the typical JavaScript error messages, discuss their common causes, and how to trap and handle them so you don’t lose your audience.

JavaScript can raise object or syntax errors for several reasons: bad user input, bad data types, or simple typos in your code. By default, all JavaScript errors (depending on the browser version and the settings) produce an alert dialog asking users if they wish to debug. The dialog displays the line number and an error message, such as “Object expected” or “Character Expected” and (in some cases) shows additional information?such as the missing character. Netscape Navigator and Internet Explorer handle errors differently, so I’ll show you ways to trap and handle errors in both browsers.

Using the Throw, Try, and Catch Statements
Microsoft JScript version 5, which ships with Internet Explorer 5+, introduced the throw, try and catch statements. The try and catch statements give you the ability to handle runtime errors during their execution with little to no performance loss. JScript 5 also introduced the Error object. JScript throws instances of the Error object whenever an error occurs in your code. The try statement lets you invoke and “try” to execute a function or code block. When there are no errors the code executes; otherwise, you can catch the error object in a “catch” block, and handle the error in a more user-friendly manner.

Author Note: With the ECMAScript standards in version 2, you can use either the try/catch or the onerror event to trap and handle your errors. Netscape Navigator 6 and Internet Explorer 5+ support them both. Note that these methods will not work in browsers earlier than version 5; however, for IE-only clients you can use client-side VBScript which has an “On Error Resume Next” statement to prevent automatic error message displays.

The error object has two properties: number and description. The number property contains a two-byte integer. To get the “real” error number, you must mask this integer with 0xffff using the bit manipulation operator (the ampersand & character). The description property returns a string containing a description of the error.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.Displaying Custom Error Messages
A more interactive way to handle an error is to give your audience an option to continue viewing the page or return to the preceding page or to some other appropriate location. Listing 3 uses the confirm method to display a custom message telling users they can click OK to continue viewing the page or click Cancel to go somewhere else. If the confirm method returns false, the user clicked Cancel as opposed to OK, and the code redirects the user. If the confirm method returns true, the code does nothing. Try it now.

Trapping Errors with an onerror Event Handler
In JavaScript 1.1 Netscape introduced the error event and the onerror event handler. The error event gives you the ability to handle image and document load errors. To use the onerror event, you must provide a function to handle the errors. Then you simply call your function with the onerror event handler. (See Figure 3)

Unlike other events, the onerror event automatically receives 3 parameters:

  • errorMessage?the error message associated with the current error
  • url?the URL of the page in which the error has occurred
  • line?the line number at which your error has taken place
Author note: onerror works in both Netscape and Internet Explorer, but be aware that Internet Explorer does not handle the onerror attribute of the tag correctly. Also, in Netscape (but not IE) the window object has an onerror property that?if set to null?prevents the display of all runtime errors, but that’s not the best way to handle errors.

The value returned by onerror determines whether the browser displays a standard error message. If you return true, the browser does not display a message. If you return false, the browser displays the standard error message in the JavaScript console.

Another way to catch errors is to use the onerror event. The JavaScript engine raises the onerror event whenever an error occurs, so you can use it to set a global error trap. The code in Listing 4 sets the onerror event handler so it points to a function called handleErrors. With the onerror event handler set, the script engine executes the handleErrors function whenever any error occurs. The function returns true to suppress the standard error message. Try it now.

Figure 4 shows the result of catching the error with the onerror event and handling it in a way that improves the user experience. Again, in a real world situation I do not recommend displaying the technical error information.

Once again, with the ECMAScript standards in version 2, you can use either the try/catch or the onerror event to trap and handle your errors. Netscape Navigator 6 and Internet Explorer 5+ support them both. Whichever method you choose, always trap for errors, and handle them in a non-intrusive manner.

devx-admin

devx-admin

Share the Post:
Chinese 5G Limitation

Germany Considers Limiting Chinese 5G Tech

A recent report has put forth the possibility that Germany’s Federal Ministry of the Interior and Community may consider limiting the use of Chinese 5G

Modern Warfare

The Barak Tank is Transforming Modern Warfare

The Barak tank is a groundbreaking addition to the Israeli Defense Forces’ arsenal, significantly enhancing their combat capabilities. This AI-powered military vehicle is expected to

AI Cheating Growth

AI Plagiarism Challenges Shake Academic Integrity

As generative AI technologies like ChatGPT become increasingly prevalent among students and raise concerns about widespread cheating, prominent universities have halted their use of AI

US Commitment

US Approves Sustainable Battery Research

The US Department of Energy has revealed a $325 million commitment in the research of innovative battery types, designed to enable solar and wind power

Netanyahu Musk AI

Netanyahu and Musk Discuss AI Future

On September 22, 2023, Israeli Prime Minister Benjamin Netanyahu met with entrepreneur Elon Musk in San Francisco prior to attending the United Nations. In a

Chinese 5G Limitation

Germany Considers Limiting Chinese 5G Tech

A recent report has put forth the possibility that Germany’s Federal Ministry of the Interior and Community may consider limiting the use of Chinese 5G technology by local network providers

Modern Warfare

The Barak Tank is Transforming Modern Warfare

The Barak tank is a groundbreaking addition to the Israeli Defense Forces’ arsenal, significantly enhancing their combat capabilities. This AI-powered military vehicle is expected to transform the way modern warfare

AI Cheating Growth

AI Plagiarism Challenges Shake Academic Integrity

As generative AI technologies like ChatGPT become increasingly prevalent among students and raise concerns about widespread cheating, prominent universities have halted their use of AI detection software, such as Turnitin’s

US Commitment

US Approves Sustainable Battery Research

The US Department of Energy has revealed a $325 million commitment in the research of innovative battery types, designed to enable solar and wind power as continuous, 24-hour energy sources.

Netanyahu Musk AI

Netanyahu and Musk Discuss AI Future

On September 22, 2023, Israeli Prime Minister Benjamin Netanyahu met with entrepreneur Elon Musk in San Francisco prior to attending the United Nations. In a live-streamed discussion, Netanyahu lauded Musk

Urban Gardening

Creating Thriving Cities Through Urban Gardening

The rising popularity of urban gardening is receiving increased recognition for its numerous advantages, as demonstrated in a recent study featured in the Environmental Research Letters journal. Carried out by

What You Need to Know About Cloud Security Strategies

What You Need to Know About Cloud Security Strategies

Today, many businesses are adopting cloud computing services. As a result, it’s important to recognize that security measures for data in the cloud are different from those in traditional on-premises

Romanian Energy Security

Eastern Europe is Achieving Energy Security

Canada and Romania have solidified their commitment to energy security and independence from Russian energy exports by signing a $3-billion export development agreement. The deal is centered on constructing two

Seamless Integration

Unlocking Seamless Smart Home Integration

The vision of an intelligently organized and interconnected smart home that conserves time, energy, and resources has long been desired by many homeowners. However, this aspiration has often been hindered

New Algorithm

MicroAlgo’s Groundbreaking Algorithm

MicroAlgo Inc. has revealed the creation of a knowledge-augmented backtracking search algorithm, developed through extensive research in evolutionary computational techniques. The algorithm is designed to boost problem-solving effectiveness, precision, and

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses