• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL

Chapter 3. Advanced DHTML Techniques > Handling Errors on the Fly

Handling Errors on the Fly

No one likes them, but errors are a fact of life. Whenever you are creating anything with JavaScript, errors will occur, and this is not always due to poor programming. Often it is caused by a glitch in the browser or a fluke in your code’s logic. Errors occur either while the page is loading (compile-time errors) or after the page has loaded (runtime errors). Compile-time errors are geneally due to poor scripting, and thus require you to rethink your code, you can control runtime errors so that the visitor is unaware that anything has gone wrong.

To handle errors (gracefully):

function handleError() {...}

Add the function handleError() to your JavaScript (Code 3.22). This function can contain anything you want, but for this example, I have it simply alerting us that an error has occurred.

Code 3.22. The handleError() function is triggered whenever an error event is generated in the window.

→ Transitional//EN" "http://www.w3.org/TR/
→ xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
→ xml:lang="en">
        <meta http-equiv="content-type"
        → content="text/html;charset=utf-8" />
        <title>DHTML &amp CSS Advanced |
        → Handling Errors</title>
        <script type="text/javascript"
        → language="javascript">
        function handleError() {
								alert('An error has occurred');
								return true;
								window.onerror = handleError;
        <a href="javascript:troubleMaker()">Click me to cause some trouble.</a>


window.onerror = handleError;

Add a global event handler for the window to trigger the function handleError() when there is an error.

<a href="javascript:
→ troubleMaker()">...</a>

Whenever a runtime error occurs—for example you try to trigger a function that does not exist (Figure 3.21)—the function handleError() goes into action (Figure 3.22).

Figure 3.21. An unassuming link on the page, which triggers a JavaScript function...

Figure 3.22. ...but the function does not exist so an alert appears.



Not a subscriber?

Start A Free Trial

  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint