Sams Teach Yourself JavaScript in 24 Hours Free Open Book

Sams Teach Yourself JavaScript in 24 Hours

Previous Page
Next Page

Creating Error Handlers

In some cases, there may be times when an error message is unavoidable and, in a large JavaScript application, errors are bound to happen. Your scripts can respond to errors in a friendlier way using error handlers.

Using the onerror Property

You can set up an error handler by assigning a function to the onerror property of the window object. When an error occurs in a script in the document, the browser calls the function you specify instead of the normal error dialog. For example, these statements set up a function that displays a simple message when an error occurs:

function errmsg(message,url,line) {
   alert("There wasn"t an error. Nothing to see here.");
   return true;
}
window.onerror=errmsg;

These statements define a function, errmsg(), which handles errors by displaying a simple dialog. The last statement assigns the errmsg() function to the window.onerror property.

The return true; statement tells the browser that this function has handled the error, and prevents the standard error dialog from being displayed. If you use return false; instead, the standard error dialog will be displayed after your function exits.

By the Way

You can't define an onError event handler in HTML. You must define it using the window.onerror property as shown here.


Displaying Information About the Error

When the browser calls your error-handling function, it passes three parameters: the error message, the URL of the document where the error happened, and the line number. The simple error handler in the previous example didn't use these values. You can create a more sophisticated handler that displays the information.

Did you Know?

As usual, you can download this hour's examples from this book's website.


Listing 16.1 shows a complete example including an enhanced errmsg() function. This version displays the error message, URL, and line number in a dialog box.

Listing 16.1. Handling Errors with a JavaScript Function

<html><head>
<title>Error handling test</title>
<script language="JavaScript" type="text/javascript">
function errmsg(message,url,line) {
   amsg = "A JavaScript error has occurred. Please let us know about it.\n";
   amsg += "Error Message: " + message + "\n";
   amsg += "URL: " + url + "\n";
   amsg += "Line #: " + line;
   alert(amsg);
   return true;
}
window.onerror=errmsg;
</script>
</head>
<body>
<h1> Error handling test</h1>
<p>This page includes a JavaScript function to handle errors.
Test it by clicking the button below.</p>
<form>
   <input type="button" value="ERROR" onClick="garble">
</form>
</body>
</html>

This example includes a button with a nonsensical event handler. To test the error handler, click the button to generate an error. Figure 16.2 shows the example in action in Internet Explorer with the alert message displayed.

Figure 16.2. The error-handler example in action.


Did you Know?

If you try to use an error handler and still get system error messages, make sure there isn't a syntax error in your error handler itself.


Using try and catch

A more modern way of handling errors, supported by the latest browsers, is the try and catch keywords. To use it, include the try keyword, then a block of code (within braces) that might cause an error, then the catch keyword, and a block of code to handle the error:

try {
  DoThis();
} catch(err) {
  alert(err.description);
}

The TRy block of code always executes. If it generates an error, the catch block is executed. If there is no error, the catch block does not execute.

The error-handling code is passed an argument (err in the example) indicating the type of error. This is an object with properties including name (the error name) and description (a description of the error).

Did you Know?

Handling errors with try and catch is a good way to deal with browser-specific code that might cause errors when run in the wrong browser. See the next hour for an example that uses TRy and catch to create a cross-browser AJAX function.


Previous Page
Next Page
Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


     Main Menu
Sams Teach Yourself JavaScript in 24 Hours
Table of Contents
Copyright
About the Author
Acknowledgments
Part I: Introducing the Concept of Web scripting and the JavaScript Language
Part II: Learning JavaScript Basics
Part III: Learning More About the DOM
Part IV: Working with Advanced JavaScript Features
Hour 15. Unobtrusive Scripting
Hour 16. Debugging JavaScript Applications
Avoiding Bugs
Basic Debugging Tools
Creating Error Handlers
Advanced Debugging Tools
Summary
Q&A
Quiz Questions
Quiz Answers
Exercises
Hour 17. AJAX: Remote Scripting
Hour 18. Greasemonkey: Enhancing the Web with JavaScript
Part V: Building Multimedia Applications with JavaScript
Part VI: Creating Complex Scripts
Part VII: Appendixes
Index


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele