Trapping Errors by Using Built-In Objects in JavaScript Testing

Exclusive offer: get 50% off this eBook here
JavaScript Testing Beginner's Guide

JavaScript Testing Beginner's Guide — Save 50%

Test and debug JavaScript the easy way.

$26.99    $13.50
by Yuxian Eugene Liang | August 2010 | Beginner's Guides Open Source

In this article, by Liang Yuxian Eugene, author of JavaScript Testing Beginner's Guide, we'll briefly describe what each type of built-in object is, along with its syntax, before we show some examples of how each of the built-in objects work. Do take note that the alert messages, which we will be using sparingly in the examples, are based on the Firefox browser. If you try the code on Internet Explorer, you might see different error messages.

In this article we will be specifically covering:

  • The Error object
  • The RangeError object
  • The ReferenceError object
  • The TypeError object
  • The SyntaxError object
  • The URIError object
  • The EvalError object

(For more resources on JavaScript, see here.)

The Error object

An Error is a generic exception, and it accepts an optional message that provides details of the exception. We can use the Error object by using the following syntax:

new Error(message); // message can be a string or an integer

Here's an example that shows the Error object in action. The source code for this example can be found in the file error-object.html.

<html>
<head>
<script type="text/javascript">
function factorial(x) {
if(x == 0) {
return 1;
}
else {
return x * factorial(x-1);
}
}
try {
var a = prompt("Please enter a positive integer", "");
if(a < 0){
var error = new Error(1);
alert(error.message);
alert(error.name);
throw error;
}
else if(isNaN(a)){
var error = new Error("it must be a number");
alert(error.message);
alert(error.name);
throw error;
}
var f = factorial(a);

alert(a + "! = " + f);
}
catch (error) {
if(error.message == 1) {
alert("value cannot be negative");
}
else if(error.message == "it must be a number") {
alert("value must be a number");
}
else
throw error;
}
finally {
alert("ok, all is done!");
}
</script>
</head>
<body>
</body>
</html>

You may have noticed that the structure of this code is similar to the previous examples, in which we demonstrated try, catch, finally, and throw. In this example, we have made use of what we have learned, and instead of throwing the error directly, we have used the Error object.

I need you to focus on the code given above. Notice that we have used an integer and a string as the message argument for var error, namely new Error(1) and new Error("it must be a number"). Take note that we can make use of alert() to create a pop-up window to inform the user of the error that has occurred and the name of the error, which is Error, as it is an Error object. Similarly, we can make use of the message property to create program logic for the appropriate error message.

It is important to see how the Error object works, as the following built-in objects, which we are going to learn about, work similarly to how we have seen for the Error object. (We might be able to show how we can use these errors in the console log.)

The RangeError object

A RangeError occurs when a number is out of its appropriate range. The syntax is similar to what we have seen for the Error object. Here's the syntax for RangeError:

new RangeError(message);

message can either be a string or an integer.

<html>
<head>
<script type="text/javascript">
try {
var anArray = new Array(-1);
// an array length must be positive
}
catch (error) {
alert(error.message);
alert(error.name);
}
finally {
alert("ok, all is done!");
}
</script>
</head>
<body>
</body>
</html>

We'll start with a simple example to show how this works. Check out the following code that can be found in the source code folder, in the file rangeerror.html:

When you run this example, you should see an alert window informing you that the array is of an invalid length. After this alert window, you should receive another alert window telling you that The error is RangeError, as this is a RangeError object. If you look at the code carefully, you will see that I have deliberately created this error by giving a negative value to the array's length (array's length must be positive).

The ReferenceError object

A ReferenceError occurs when a variable, object, function, or array that you have referenced does not exist. The syntax is similar to what you have seen so far and it is as follows:

new ReferenceError(message);

message can either be a string or an integer.

As this is pretty straightforward, I'll dive right into the next example. The code for the following example can be found in the source code folder, in the file referenceerror.html.

<html>
<head>
<script type="text/javascript">
try {
x = y;
// notice that y is not defined
// an array length must be positive

}
catch (error) {
alert(error);
alert(error.message);
alert(error.name);
}
finally {
alert("ok, all is done!");
}
</script>
</head>
<body>
</body>
</html>

Take note that y is not defined, and we are expecting to catch this error in the catch block. Now try the previous example in your Firefox browser. You should receive four alert windows regarding the errors, with each window giving you a different message. The messages are as follows:

  • ReferenceError: y is not defined
  • y is not defined
  • ReferenceError
  • ok, all is done

If you are using Internet Explorer, you will receive slightly different messages. You will see the following messages:

  • [object Error] message
  • y is undefined
  • TypeError
  • ok, all is done

The TypeError object

A TypeError is thrown when we try to access a value that is of the wrong type. The syntax is as follows:

new TypeError(message); // message can be a string or an integer and
it is optional

An example of TypeError is as follows:

<html>
<head>
<script type="text/javascript">
try {
y = 1
var test = function weird() {
var foo = "weird string";
}
y = test.foo(); // foo is not a function
}
catch (error) {
alert(error);
alert(error.message);
alert(error.name);
}
finally {
alert("ok, all is done!");
}
</script>
</head>
<body>
</body>
</html>

If you try running this code in Firefox, you should receive an alert box stating that it is a TypeError. This is because test.foo() is not a function, and this results in a TypeError. JavaScript is capable of finding out what kind of error has been caught. Similarly, you can use the traditional method of throwing your own TypeError(), by uncommenting the code.

The following built-in objects are less used, so we'll just move through quickly with the syntax of the built-in objects.

JavaScript Testing Beginner's Guide Test and debug JavaScript the easy way.
Published: August 2010
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

(For more resources on JavaScript, see here.)

The SyntaxError object

A SyntaxError occurs when there is an error in syntax. The syntax for SyntaxError is as follows:

new SyntaxError([message,[,,[,filename[, lineNumber]]]); // message
can be a string or an integer and it is optional

Take note that the filename and lineNumber parameters are non-standard, and they should be avoided if possible.

The URIError object

A URIError occurs when a malformed URI is encountered. The syntax is as follows:

new URIError([message,[,filename[, lineNumber]]]);

Similar to SyntaxError, take note that the filename and lineNumber parameters are non-standard, and they should be avoided if possible.

The EvalError object

An EvalError occurs when an eval statement is used incorrectly or contains an error other than a syntax error.

new EvalError([message,[,filename[, lineNumber]]]);// message can be a
string or an integer and it is optional

Similar to SyntaxError and URIError, take note that the filename and lineNumber parameters are non-standard, and they should be avoided if possible.

Summary

In the above article, we have covered:

  • The Error object
  • The RangeError object
  • The ReferenceError object
  • The TypeError object
  • The SyntaxError object
  • The URIError object
  • The EvalError object

Further resources on this subject:


JavaScript Testing Beginner's Guide Test and debug JavaScript the easy way.
Published: August 2010
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

About the Author :


Yuxian Eugene Liang

Eugene enjoys solving difficult problems creatively in the form of building web applications using Python/Django and JavaScript/JQuery. He also enjoys doing research related to the areas of recommendation algorithms, link analysis, data visualization, data mining, information retrieval, business intelligence, and intelligent user interfaces. He has recently started a personal blog at http://www.liangeugene.com

Books From Packt


JSF 2.0 Cookbook
JSF 2.0 Cookbook

jQuery 1.4 Reference Guide
jQuery 1.4 Reference Guide

YUI 2.8: Learning the Library
YUI 2.8: Learning the Library

Object-Oriented JavaScript
Object-Oriented JavaScript

Joomla! 1.5 JavaScript jQuery
Joomla! 1.5 JavaScript jQuery

Learning Ext JS 3.0
Learning Ext JS 3.0

JSF 1.2 Components
JSF 1.2 Components

Alfresco 3 Web Content Management
Alfresco 3 Web Content Management


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
5
S
t
a
p
k
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software