Categories
JavaScript

JavaScript error messages, error handling and try catch

To avoid errors being presented to the end user:

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

But of course, the best way to handle this (after IE 5), is by using try{ } catch { } structures:

<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>

Note how the script has to be set as javascript1.5 to avoid old browsers to run into problems with try catch.

The following table indicates what’s available from the “e” error object passed to the catch statement, and what browsers support it:

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
 From inside a try statement, you can throw errors yourself:
throw err;

Leave a Reply

Your email address will not be published. Required fields are marked *