Home arrow JavaScript arrow Page 3 - More on Variables, Functions, and Flow Control
JAVASCRIPT

More on Variables, Functions, and Flow Control


In this second part of a two-part series, you'll learn how to delay a function call, handle script errors gracefully, and more. It is excerpted from chapter 4 of the JavaScript & DHTML Cookbook, Second Edition, written by Danny Goodman (O'Reilly, 2008; ISBN: 0596514085). Copyright 2008 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 5 stars5 stars5 stars5 stars5 stars / 4
December 14, 2009
TABLE OF CONTENTS:
  1. · More on Variables, Functions, and Flow Control
  2. · 4.6 Branching Execution Based on Conditions
  3. · 4.7 Handling Script Errors Gracefully
  4. · 4.8 Improving Script Performance

print this article
SEARCH DEVARTICLES

More on Variables, Functions, and Flow Control - 4.7 Handling Script Errors Gracefully
(Page 3 of 4 )

Problem

You want to process all script errors out of view of users, and thus prevent the browser from reporting errors to the user.

Solution

The quick-and-dirty, backward-compatible way to prevent runtime script errors from showing themselves to users is to include the following statements in a script within the head portion of a page: 

  function doNothing() {return true;}
  window.onerror = doNothing;

This won't stop compile-time script errors (e.g., syntax errors that the interpreter discovers as the page loads). It also won't reveal to you, the programmer, where errors lurk in your code. Add this only if you need to deploy a page before you have fully debugged the code (essentially sweeping bugs under the rug); remove it to test your code.

In IE 5 or later, Mozilla, Safari, and Opera 7 or later, you can use more formal error (exception) handling. If you are allowing your pages to load in older browsers, you may need to prevent those browsers from coming into contact with the error-handling code. To prevent earlier browsers from tripping up on the specialized syntax used for this type of processing, embed these statements in <script> tags that specify JavaScript 1.5 as the language attribute (language="JavaScript1.5").

Wrap statements that might cause (throw) an exception in a try/catch construction. The statement to execute goes into the try section, while the catch section processes any exception that occurs:

  <script type="text/javascript" language="JavaScript1.5">
  function myFunc() {
     
try {
         
// statement(s) that could throw an error if various conditions aren't right
      }
      catch(e) {
         
// statements that handle the exception (error object passed to e variable)
     
}
  }
  </script>

Even if you do nothing in the required catch section, the exception in the try section is not fatal. Subsequent processing in the function, if any, goes on, provided it is not dependent upon values created in the try section. Or, you can bypass further processing in the function and gracefully exit by executing a return statement inside the catch section.

Discussion

Each thrown exception generates an instance of the JavaScript Error object. A reference to this object reaches the catch portion of a try/catch construction as a parameter to the catch clause. Script statements inside the catch clause may examine properties of the object to learn more about the nature of the error. Only a couple of properties are officially sanctioned in the ECMAScript standard so far, but some browsers implement additional properties that contain the same kind of information you see in script error messages. Table 4-2 lists informative Error object properties and their browser support.

 

Table 4-2. Error object properties

Property IE/Windows Mozilla Safari Opera Description
description 5 n/a n/a n/a Plain-language description of error
fileName n/a all n/a n/a URI of the file containing the script throwing the error 
lineNumber n/a all n/a n/a Source code line number of error
message 5.5 all all 7 Plain-language description of error (ECMA)
name 5.5 all all 7 Error type (ECMA)
number 5 n/a n/a n/a Microsoft proprietary error number
stack n/a 1.0.1 n/a n/a Multi-line string of function references leading to error

 

Error messages are never intended to be seen by users. Use the description or message property of an Error object in your own exception handling to decide how to process the exception. Unfortunately, the precise message from the various browsers is not always identical for a given error. For example, if you try to reference an undefined object, IE reports the description string as:

  'myObject' is undefined

Mozilla, on the other hand, reports:

  myObject is not defined

This makes cross-browser exception handling a bit difficult. In this case, you could try to fudge it by performing string lookups (regular expression matches) for the object reference and the fragment "defined" as in the following:

  try {
     
window.onmouseover = trackPosition;
  }
  catch(e) {
     
var msg = (e.message) ? e.message : e.description;
      if (/trackPosition/.exec(msg) && /defined/.exec(msg)) {
          // trackPosition function does not exist within page scope
      }
  }

You can also intentionally throw an exception as a way to build exception handling into your own processing. The following function is a variation of a form validation function that tests for the entry of only a number in a text box. The try clause tests for an incorrect value. If found, the clause creates its own instance of an Error object and uses the throw method to trigger an exception. Of course, the thrown exception is immediately caught by the following catch clause, which displays the alert message and refocuses the text box in question:

  function processNumber(inputField) {
     
try {
         
var inpVal = parseInt(inputField.value, 10);
         
if (isNaN(inpVal)) {
             
var msg = "Please enter a number only.";
             
var err = new Error(msg);
             
if (!err.message) {
                 
err.message = msg;
             
}
             
throw err;
         
}
         
// it's safe to process number
here
      }
      catch (e) {
         
alert(e.message);
         
inputField.focus();
         
inputField.select();
     
}
  }

This kind of function is invoked by both a change event handler for the text field and a batch validation routine, as described in Chapter 8.


blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials