Tải bản đầy đủ (.pdf) (24 trang)

ASP.NET AJAX Programmer’s Reference - Chapter 3 doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (308.72 KB, 24 trang )

Built-In and Custom
Exception Types
The previous chapter discussed two important ASP.NET AJAX JavaScript Error type extension
functions named
create and popStackFrame . This chapter shows you how the ASP.NET AJAX
client-side script framework uses these two JavaScript functions to provide you with a set of .NET-
like exception types. The chapter then presents you with a recipe for developing your own custom
exception types in the ASP.NET AJAX client-side framework, and shows you how to use the recipe
to implement a custom exception type.
ASP.NET AJAX Built-In Exception Types
One of the great things about the .NET Framework is that it comes with a rich set of exception
types that address different programming scenarios. For example, you can use the

ArgumentNullException type in your method to raise an exception to inform the callers if your
method does not accept
null values for a particular parameter. Exception programming is one of
the fundamental aspects of any modern programming framework.
The ASP.NET AJAX client-side framework presents a rich set of exception types that emulate many
of the .NET exception types to make client-side exception programming more like server-side
.NET exception programming. This section provides in-depth coverage of the ASP.NET AJAX
client-side framework’s built-in exception types.
ArgumentException
The .NET Framework comes with an exception type named ArgumentException . This exception
is raised when a method is invoked and one of the parameters passed into the method does not
meet the requirements that the method expects of the parameter. The .NET
ArgumentException
exposes a read-only property named
ParamName that specifies the name of the parameter that
caused the exception to occur.
c03.indd 53c03.indd 53 8/20/07 5:50:28 PM8/20/07 5:50:28 PM
Chapter 3: Built-In and Custom Exception Types


54
The ASP.NET AJAX client-side framework extends JavaScript to add support for a similar exception type
named
ArgumentException , which belongs to a namespace called Sys . (I discuss namespaces in future
chapters.) This JavaScript
ArgumentException exposes two properties named paramName and name . The

name property, like the name property of any JavaScript exception, contains the string that uniquely identi-
fies the exception type. The
paramName property is the equivalent of the .NET ArgumentException
type’s
ParamName property.
The ASP.NET AJAX client-side framework also extends the functionality of the JavaScript
Error type
to add support for a static method named
argument that automatically creates an instance of the
Sys.ArgumentException exception and returns the instance to its caller. The best way to understand
what this function does is to take a look at its internal implementation:
Error.argument = function(a, c)
{
var b = ”Sys.ArgumentException: “ +
(c ? c : Sys.Res.argument);
if(a)
b += “\n” + String.format(Sys.Res.paramName, a);
var d = Error.create(b,
{ name : “Sys.ArgumentException”,
paramName : a});
d.popStackFrame();
return d;
};

Notice that the argument static method takes two arguments. The first argument is a string that contains
the name of the parameter that caused the exception to occur. The second argument is a string that con-
tains the error message. The argument function internally calls the
create static method discussed in
Chapter 2 :
var d = Error.create(b,
{ name : “Sys.ArgumentException”,
paramName : a});
The create static method takes an object as its second parameter. This object provides extra information
about the
Error object being created. Note that the argument method passes an object literal as the sec-
ond parameter of the
create method. This object literal specifies the string that uniquely identifies the
exception and the parameter that caused the exception.
The
Sys.ArgumentException does not come with a constructor function, so you cannot instantiate it
using the
new operator. Instead, you must use the argument static function of the JavaScript Error
object to instantiate an instance of this exception.
The
validateInput function in the following page code raises a Sys.ArgumentException exception if
the parameter passed into it does not meet the requirement specified in the regular expression. The

clickCallback function catches this exception in its catch block and displays the value of the excep-
tion object’s
message property.
c03.indd 54c03.indd 54 8/20/07 5:50:30 PM8/20/07 5:50:30 PM
Chapter 3: Built-In and Custom Exception Types
55
<%@ Page Language=”C#” %>


<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Transitional//EN”
“ /><html xmlns=” /><head id=”Head1” runat=”server”>
<title>Untitled Page</title>
<script language=”javascript” type=”text/javascript”>
function validateInput(input)
{
var reg = new RegExp(“(\\d\\d)[-/](\\d\\d)[-/](\\d\\d(?:\\d\\d)?)”);
var date = reg.exec(input);
if (date == null)
{
var err = Error.argument(“input”, “Invalid date!”);
throw err;
}
}

function clickCallback()
{
var date = document.getElementById(“date”);
try
{
validateInput(date.value);
}
catch (e)
{
alert(e.message);
date.value=””;
}
}


</script>
</head>
<body>
<form id=”form1” runat=”server”>
<asp:ScriptManager runat=”server”
ID=”ScriptManager1” />
Enter date: <input type=”text” id=”date” />&nbsp;
<input type=”button” value=”Validate”
onclick=”clickCallback()” />
</form>
</body>
</html>
As Figure 3-1 shows, the message property displays the type of the exception (which in this case is
Sys.ArgumentException ), the exception message, and the name of the parameter that caused the
exception to occur.
c03.indd 55c03.indd 55 8/20/07 5:50:31 PM8/20/07 5:50:31 PM
Chapter 3: Built-In and Custom Exception Types
56
ArgumentNullException
The .NET Framework includes an exception type named ArgumentNullException . This exception is
raised when a method is invoked and one of the parameters passed into it is
null . As you can see,

ArgumentNullException is more specific than ArgumentException .
The ASP.NET AJAX client-side framework follows this .NET pattern and introduces an exception type
named
Sys.ArgumentNullException , which is more specific than Sys.ArgumentException . Just like
its .NET counterpart,
Sys.ArgumentNullException is raised only when one of the parameters passed

into a JavaScript function is
null .
The ASP.NET AJAX client-side framework also extends the JavaScript
Error type to add support for a new
static method named
argumentNull , which hides the instantiation of the Sys.ArgumentNull Exception
object from its callers. As the following code shows, the internal implementation of the
argumentNull
method is the same as the
argument method:
Error.argumentNull = function(a, c)
{
var b = ”Sys.ArgumentNullException: “ +
(c ? c : Sys.Res.argumentNull);
if(a)
b += “\n” + String.format(Sys.Res.paramName, a);
var d = Error.create(b,
{ name : “Sys.ArgumentNullException”,
paramName : a });
d.popStackFrame();
return d;
};
As you can see, the argumentNull static method takes the same arguments as the argument static
method discussed in the previous section. The only difference between the two methods is the value part
of the first name/value pair of the object literal passed into the
Error type’s create static method. This
value is a string that uniquely identifies an exception type for other exception types.
The
validateInput function in the following code uses the argumentNull static method of the Error
object to create and raise a

Sys.ArgumentNullException when the user does not enter a date into the
text box. The
clickCallback function catches this exception in its catch block and displays the value
of the exception object’s
message property.
Figure 3-1
c03.indd 56c03.indd 56 8/20/07 5:50:32 PM8/20/07 5:50:32 PM
Chapter 3: Built-In and Custom Exception Types
57
<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Transitional//EN”
“ /><html xmlns=” /><head id=”Head1” runat=”server”>
<title>Untitled Page</title>
<script language=”javascript” type=”text/javascript”>
function validateInput(input)
{
if (input == null || input.trim() == “”)
{
var er = Error.argumentNull(“input”, “Date cannot be null!”);
throw er;
}
var reg = new RegExp(“(\\d\\d)[-/](\\d\\d)[-/](\\d\\d(?:\\d\\d)?)”);
var date = reg.exec(input);
if (date == null)
{
var err = Error.argument(“input”,“Invalid date!”);
throw err;
}

}

function clickCallback()
{
var date = document.getElementById(“date”);
try
{
validateInput(date.value);
}
catch (e)
{
alert(e.message);
date.value=””;
}
}

</script>
</head>
<body>
<form id=”form1” runat=”server”>
<asp:ScriptManager runat=”server”
ID=”ScriptManager1” />
Enter date: <input type=”text” id=”date” />&nbsp;
<input type=”button” value=”Validate”
onclick=”clickCallback()” />
</form>
</body>
</html>
c03.indd 57c03.indd 57 8/20/07 5:50:33 PM8/20/07 5:50:33 PM
Chapter 3: Built-In and Custom Exception Types

58
As Figure 3-2 shows, the message property contains the exception type ( Sys.ArgumentNullException ),
the exception message passed into the
argumentNull function, and the name of the parameter that
caused the exception to occur.
Figure 3-2
ArgumentOutOfRangeException
The .NET Framework includes an exception of type ArgumentOutOfRangeException . This exception is
raised when a method is invoked and one of the parameters passed into it is out of the range of valid
values.
ArgumentOutOfRangeException features two important properties named ParamName and

ActualValue , which contain the name and value of the parameter that caused the exception to occur,
respectively.
Following the same .NET pattern, the ASP.NET AJAX client-side script framework includes an exception
of type
Sys.ArgumentOutOfRangeException , which exposes the same two paramName and actual-
Value
properties. In addition, the ASP.NET AJAX client-side framework extends the JavaScript Error
type to add support for a new static method named
argumentOutOfRange that hides the instantiation of
the
Sys.ArgumentOutOfRangeException . The following code presents the internal implementation
of this static method:
Error.argumentOutOfRange = function(c, a, d)
{
var b=”Sys.ArgumentOutOfRangeException: “ +
(d ? d : Sys.Res.argumentOutOfRange);
if(c)
b += “\n” + String.format(Sys.Res.paramName, c);

if(typeof a !== “undefined” && a !== null)
b += “\n” + String.format(Sys.Res.actualValue, a);

var e = Error.create(b,
{name : “Sys.ArgumentOutOfRangeException”,
paramName : c, actualValue : a});
e.popStackFrame();
return e;
};
The argumentOutOfRange method takes three arguments. The first and second arguments are the name
and value of the parameter that caused the exception to occur. The third argument is the exception
c03.indd 58c03.indd 58 8/20/07 5:50:33 PM8/20/07 5:50:33 PM
Chapter 3: Built-In and Custom Exception Types
59
message that provides more information about the exception. The argumentOutOfRange method first
creates a string that contains the values of the three arguments:
var b=”Sys.ArgumentOutOfRangeException: “ +
(d ? d : Sys.Res.argumentOutOfRange);
if(c)
b += “\n” + String.format(Sys.Res.paramName, c);
if(typeof a !== “undefined” && a !== null)
b += “\n” + String.format(Sys.Res.actualValue, a);
Then, it calls the create static method of the JavaScript Error type, passing in two parameters to create
the associated
Error object. The first parameter is the previously mentioned string. The second parameter
is a JavaScript object literal that contains information about the
Sys.ArgumentOutOfRangeException
exception. Finally, the
argumentOutOfRange function calls the popStackFrame function to reset the val-
ues of the

Error object’s fileName and lineNumber properties (discussed in Chapter 2 ).
As the boldfaced portion of the following code shows, if the date entered in the text box is not in the
specified range, the
validateInput function invokes the argumentOutOfRange function to create a

Sys.ArgumentOutOfRangeException . The clickCallback function catches this exception in its

catch block and displays the pop-up message shown in Figure 3-3 . The message property of the Error
object displays the exception type (
Sys.ArgumentOutOfRangeException ), the exception message
passed into the
argumentOutOfRange function, and the name and value of the parameter that caused
the exception to occur.
<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Transitional//EN”
“ /><html xmlns=” /><head id=”Head1” runat=”server”>
<title>Untitled Page</title>
<script language=”javascript” type=”text/javascript”>
function validateInput(input)
{
if (input == null || input.trim() == “”)
{
var er = Error.argumentNull(“input”,“Date cannot be null!”);
throw er;
}
var reg = new RegExp(“(\\d\\d)[-](\\d\\d)[-](\\d\\d\\d\\d)”);
var date = reg.exec(input);
if (date == null)

{
var err = Error.argument(“input”,“Invalid date!”);
throw err;
}

var ar = input.split(“-”);

if (ar[2] < 1900 || ar[2] > 2008)
(continued)
c03.indd 59c03.indd 59 8/20/07 5:50:34 PM8/20/07 5:50:34 PM
Chapter 3: Built-In and Custom Exception Types
60
{
var err2=Error.argumentOutOfRange(“input”,input);
throw err2;
}
}

function clickCallback()
{
var date = document.getElementById(“date”);
try
{
validateInput(date.value);
}
catch (e)
{
alert(e.message);
date.value=””;
}

}

</script>
</head>
<body>
<form id=”form1” runat=”server”>
<asp:ScriptManager runat=”server” ID=”ScriptManager1”/>
Enter date: <input type=”text” id=”date” />&nbsp;
<input type=”button” value=”Validate”
onclick=”clickCallback()” />
</form>
</body>
</html>
Figure 3-3
ArgumentTypeException
When you implement a method in the .NET Framework with a given set of parameters of specific types,
you can rest assured that the Framework will ensure that users call your method with only the types of
parameters that your method expects.
c03.indd 60c03.indd 60 8/20/07 5:50:34 PM8/20/07 5:50:34 PM
Chapter 3: Built-In and Custom Exception Types
61
The ASP.NET AJAX client-side framework includes an exception type named Sys.ArgumentTypeEx
ception
that you can call from within your JavaScript functions to make programming against your
functions more like programming against .NET methods.
The
Sys.ArgumentTypeException exception is raised when a method is invoked and one of the
parameters passed into it is not of the type that the method expects. This exception, just like all other
exceptions in the ASP.NET AJAX client-side framework, does not come with a constructor function. This
means that you cannot use the

new operator to instantiate it. Instead, the ASP.NET AJAX client-side
framework includes a new static method named
argumentType to the JavaScript Error type that auto-
matically instantiates this exception under the hood.
This method takes four arguments. The first, second, and third arguments contain the name, actual type,
and expected type of the parameter that caused the exception to occur. The last argument is the excep-
tion message that provides more information about the exception.
The
validateInput function in the following code throws a Sys.ArgumentTypeException exception
when the input is not a valid date value. The
clickCallback function then catches this exception in its

catch block and displays the message shown in Figure 3-4 . Note that the catch block uses the value of
the exception object’s
name property to determine the type of the exception.
<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Transitional//EN”
“ /><html xmlns=” /><head id=”Head1” runat=”server”>
<title>Untitled Page</title>
<script language=”javascript” type=”text/javascript”>
function validateInput(input)
{
if (input == null || input.trim() == “”)
{
var er = Error.argumentNull(“input”,“Date cannot be null!”);
throw er;
}
var reg = new RegExp(“(\\d\\d)[-/](\\d\\d)[-/](\\d\\d(?:\\d\\d)?)”);

var date = reg.exec(input);
if (date == null)
{
var err = Error.argumentType(“input”, null, Date, “Invalid type!”);
throw err;
}

var ar = input.split(“-”);

if (ar[2] < 1900 || ar[2] > 2008)
{
(continued)
c03.indd 61c03.indd 61 8/20/07 5:50:35 PM8/20/07 5:50:35 PM
Chapter 3: Built-In and Custom Exception Types
62
var err2=Error.argumentOutOfRange(“input”,input);
throw err2;
}
}

function clickCallback()
{
var date = document.getElementById(“date”);
try
{
validateInput(date.value);
}
catch (e)
{
if (e.name == “Sys.ArgumentTypeException ”)

alert(e.message + “\nExpected Type : “ +
e.expectedType.getName());
else
alert(e.message);
date.value=””;
}
}

</script>
</head>
<body>
<form id=”form1” runat=”server”>
<asp:ScriptManager runat=”server” ID=”ScriptManager1”/>
Enter date: <input type=”text” id=”date” />&nbsp;
<input type=”button” value=”Validate”
onclick=”clickCallback()” />
</form>
</body>
</html>
Figure 3-4
c03.indd 62c03.indd 62 8/20/07 5:50:36 PM8/20/07 5:50:36 PM
Chapter 3: Built-In and Custom Exception Types
63
Now take a look at the internal implementation of the argumentType function in the following code:
Error.argumentType = function(d, c, b, e)
{
var a = ”Sys.ArgumentTypeException: “ +
(e ? e : “”);
if(c && b)
a += String.format(Sys.Res.argumentTypeWithTypes, c.getName(), b.getName());

else
a += Sys.Res.argumentType;
if(d)
a += “\n” + String.format(Sys.Res.paramName, d);
var f = Error.create(a,
{name : “Sys.ArgumentTypeException”,
paramName : d, actualType : c,
expectedType : b});
f.popStackFrame();
return f
};
The argumentType method first builds a string that contains the following:
❑ The error message:
var a=”Sys.ArgumentTypeException: “ + (e ? e : “”);
❑ The names of the actual and expected types (if any):
if(c && b)
a += String.format(Sys.Res.argumentTypeWithTypes,
c.getName(), b.getName());
It then calls the create static function of the Error type, passing the following parameters to create the

Error object:
❑ The string built in the first step
❑ An object literal that provides more information about the exception. Note that this object con-
tains the following properties:
name , paramName , actualType , and expectedType :
var f = Error.create(a,
{name : “Sys.ArgumentTypeException”,
paramName : d, actualType : c,
expectedType : b});
Finally, the exception calls the popStackFrame function on the Error object to reset the values of the


fileName and lineNumber properties (discussed previously).
c03.indd 63c03.indd 63 8/20/07 5:50:36 PM8/20/07 5:50:36 PM
Chapter 3: Built-In and Custom Exception Types
64
ArgumentUndefinedException
The ASP.NET AJAX client-side framework includes an exception type named Sys.ArgumentUndefined-
Exception
. This exception is raised when a function is invoked and one of the parameters passed into it
is undefined. This exception, like all other exceptions in the ASP.NET AJAX client-side framework, does
not come with a constructor function and therefore cannot be instantiated using the
new operator. The
ASP.NET AJAX client-side framework includes a static method on the
Error type named

argumentUndefined that instantiates this exception for you. This method takes two arguments. The
first argument is the name of the parameter that caused the exception. The second argument is an
exception message that provides more information about the exception. The internal implementation of
the
argumentUndefined static method follows the same implementation pattern as any other static
method of the ASP.NET AJAX Framework’s
Error type that instantiates an exception object.
The method first builds a string that contains the exception message and the name of the parameter that
caused the exception, as follows:
var b = ”Sys.ArgumentUndefinedException: “ +
(c ? c : Sys.Res.argumentUndefined);
if(a)
b += “\n” + String.format(Sys.Res.paramName, a);
It then calls the Error object’s create static method, passing in two arguments, as shown in the follow-
ing code. The first argument is the string built in the first step. The second argument is the JavaScript

object literal that provides more information about the
Sys.ArgumentUndefinedException exception.
var d = Error.create(b,
{name : “Sys.ArgumentUndefinedException”,
paramName : a});
Next, it calls the popStackFrame JavaScript function to reset the values of the fileName and

lineNumber properties of the Error object:
d.popStackFrame();
Finally, it returns the exception object to its caller:
Error.argumentUndefined = function(a, c)
{
var b=”Sys.ArgumentUndefinedException: “ +
(c ? c : Sys.Res.argumentUndefined);
if(a)
b += “\n” + String.format(Sys.Res.paramName, a);
var d = Error.create(b,
{name : “Sys.ArgumentUndefinedException”,
paramName : a});
d.popStackFrame();
return d;
};
The validateInput function in the following example calls the argumentUndefined static method on
the
Error type to raise a Sys.ArgumentUndefinedException exception when the end user enters an
c03.indd 64c03.indd 64 8/20/07 5:50:37 PM8/20/07 5:50:37 PM
Chapter 3: Built-In and Custom Exception Types
65
undefined value into the text box. The clickCallback function then catches this exception and displays
the pop-up message shown in Figure 3-5 .

<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Transitional//EN”
“ /><html xmlns=” /><head id=”Head1” runat=”server”>
<title>Untitled Page</title>
<script language=”javascript” type=”text/javascript”>
function validateInput(input)
{
if (input == null || input.trim() == “”)
{
var er = Error.argumentNull(“input”,“Date cannot be null!”);
throw er;
}
var reg = new RegExp(“(\\d\\d)[-](\\d\\d)[-](\\d\\d\\d\\d)”);
var date = reg.exec(input);
if (date == null)
{
var err = Error.argumentUndefined(“input”, “Undefined value!”);
throw err;
}

var ar = input.split(“-”);

if (ar[2] < 1900 || ar[2] > 2008)
{
var err2=Error.argumentOutOfRange(“input”,input);
throw err2;
}
}


function clickCallback()
{
var date = document.getElementById(“date”);
try
{
validateInput(date.value);
}
catch (e)
{
alert(e.message);
date.value=””;
}
}
(continued)
c03.indd 65c03.indd 65 8/20/07 5:50:37 PM8/20/07 5:50:37 PM
Chapter 3: Built-In and Custom Exception Types
66
</script>
</head>
<body>
<form id=”form1” runat=”server”>
<asp:ScriptManager runat=”server” ID=”ScriptManager1”/>
Enter date: <input type=”text” id=”date” />&nbsp;
<input type=”button” value=”Validate”
onclick=”clickCallback()” />
</form>
</body>
</html>
Figure 3-5

InvalidOperationException
Sys.InvalidOperationException is raised when a method call fails due to reasons other than the
argument problems discussed in the previous sections. This exception object, like any other exception in
the ASP.NET AJAX client-side script framework, features a property called
name whose value uniquely
identifies the exception type. The JavaScript
Error object’s invalidOperation static method encapsu-
lates the logic that instantiates a
Sys.InvalidOperationException . This function takes a single argu-
ment that contains the exception message. Here is the internal implementation of this function:
Error.invalidOperation = function(a)
{
var c = ”Sys.InvalidOperationException: “ +
(a ? a : Sys.Res.invalidOperation),
b = Error.create(c,
{name : “Sys.InvalidOperationException”});
b.popStackFrame();
return b;
};
NotImplementedException
When you’re implementing a base class in the .NET Framework, you have two options when it comes to
the implementation of a virtual method or property of your base class. You can either provide a default
implementation for the method or property, or raise a .NET exception named
NotImplementedException .
The ASP.NET AJAX client-side script framework provides you with the same type of exception, which is
called
Sys.NotImplementedException and exposes a single name property.
c03.indd 66c03.indd 66 8/20/07 5:50:38 PM8/20/07 5:50:38 PM
Chapter 3: Built-In and Custom Exception Types
67

It shouldn’t come as a surprise that the ASP.NET AJAX client-side framework also extends the

Error object to add a static method named notImplemented to instantiate and return an instance
of the
Sys.NotImplementedException exception. This method takes a single argument, which con-
tains the exception message. As the following code shows, the internal implementation of this method
has the same implementation pattern as the internal implementation of any other ASP.NET AJAX
method on the
Error type that instantiates an exception:
Error.notImplemented = function(a)
{
var c = ”Sys.NotImplementedException: “ +
(a ? a : Sys.Res.notImplemented),
b = Error.create(c,
{name : “Sys.NotImplementedException”});
b.popStackFrame();
return b;
};
The following example defines a JavaScript class named Validator , which exposes a method named

validateInput . Note that the Validator class’s implementation of the validateInput function
simply raises a
Sys.NotImplementedException exception to inform its caller that this class does not
implement this method. In subsequent chapters, you learn how to use a subclass of this class that
implements this method.
<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Transitional//EN”
“ /><html xmlns=” /><head id=”Head1” runat=”server”>

<title>Untitled Page</title>
<script language=”javascript” type=”text/javascript”>
function Validator (name)
{
var _name = name;
this.getName = function() {return _name;};
}

Validator.prototype.validateInput = function(input)
{
var err = Error.notImplemented(“Input validation is not supported!”);
throw err;
};

function clickCallback()
{
var date = document.getElementById(“date”);
try
{
var v = new Validator(“MyValidator”);
v.validateInput(date.value);
(continued)
c03.indd 67c03.indd 67 8/20/07 5:50:38 PM8/20/07 5:50:38 PM
Chapter 3: Built-In and Custom Exception Types
68
}
catch (e)
{
alert(e.message);
date.value=””;

}
}

</script>
</head>
<body>
<form id=”form1” runat=”server”>
<asp:ScriptManager runat=”server” ID=”ScriptManager1”/>
Enter date: <input type=”text” id=”date” />&nbsp;
<input type=”button” value=”Validate”
onclick=”clickCallback()” />
</form>
</body>
</html>
ParameterCountException
When you write a method in the .NET Framework that takes a specific number of parameters of specific
types, you can rest assured that the Framework will not allow anyone to call your method with fewer
parameters than your method expects. That’s why your method does not need to check whether the
required number of parameters is passed into it.
JavaScript functions, on the other hand, allow their callers to call them with fewer parameters or no
parameters at all. To make programming against JavaScript functions more like programming against
.NET methods, the ASP.NET AJAX client-side Framework features an exception of type
Sys.Parame-
terCountException
that you can raise from within the body of your JavaScript functions to ensure that
no one can call your function with fewer parameters than expected. This exception features a single
name
property that contains the name of the exception type —
Sys.ParameterCountException .
The ASP.NET AJAX client-side Framework also extends the JavaScript

Error type to add a new member
static method named
parameterCount that encapsulates the logic that instantiates the Sys.Parame-
terCountException
exception. This method takes a single argument, which contains the exception
message. As the following code shows, the internal implementation of this exception has the same
implementation pattern as other exception-generating methods on the
Error type:
Error.parameterCount = function(a)
{
var c=”Sys.ParameterCountException: “ +
(a ? a : Sys.Res.parameterCount),
b = Error.create(c,
{name : “Sys.ParameterCountException”});
b.popStackFrame();
return b;
};
The validateInput function in the following page code throws a Sys.ParameterCountException
exception if the number of parameters passed into the function is not equal to the number of parameters
c03.indd 68c03.indd 68 8/20/07 5:50:39 PM8/20/07 5:50:39 PM
Chapter 3: Built-In and Custom Exception Types
69
that the function expects. The clickCallback function catches this exception and displays the value of
the
Error object’s message property in the pop-up message box shown in Figure 3-6 .
<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Transitional//EN”
“ /><html xmlns=” /><head id=”Head1” runat=”server”>

<title>Untitled Page</title>
<script language=”javascript” type=”text/javascript”>
function validateInput(input)
{
if (arguments.length != arguments.callee.length)
{
var err3=Error.parameterCount( “Invalid argument count!”);
throw err3;
}

if (input == null || input.trim() == “”)
{
var er = Error.argumentNull(“input”, “Date cannot be null!”);
throw er;
}
var reg = new RegExp(“(\\d\\d)[-](\\d\\d)[-](\\d\\d\\d\\d)”);
var date = reg.exec(input);
if (date == null)
{
var err = Error.argumentUndefined(“input”, “Undefined value!”);
throw err;
}

var ar = input.split(“-”);

if (ar[2] < 1900 || ar[2] > 2008)
{
var err2=Error.argumentOutOfRange(“input”,input);
throw err2;
}

}

function clickCallback()
{
var date = document.getElementById(“date”);
try
{
validateInput(date.value, 3);
}
(continued)
c03.indd 69c03.indd 69 8/20/07 5:50:39 PM8/20/07 5:50:39 PM
Chapter 3: Built-In and Custom Exception Types
70
catch (e)
{
alert(e.message);
date.value=””;
}
}

</script>
</head>
<body>
<form id=”form1” runat=”server”>
<asp:ScriptManager runat=”server” ID=”ScriptManager1”/>
Enter date: <input type=”text” id=”date” />&nbsp;
<input type=”button” value=”Validate”
onclick=”clickCallback()” />
</form>
</body>

</html>
Figure 3-6
Implementing Custom Exception Types
The previous section walked you through the internal implementation of the built-in exception types of
the ASP.NET AJAX client-side framework. This section builds on the skills you learned in the previous
section to show you how to implement your own custom exception types.
Recipe for Implementing Custom Exception Types
To implement your own custom exception type in the ASP.NET AJAX client-side script framework, the
first thing you need to do is choose an appropriate name for your custom exception type. This name
must be unique. Make sure you don’t use the exception type names of the ASP.NET AJAX built-in excep-
tion types. Also make sure you use Pascal casing and end the type name with the word
Exception .
Next, decide how many and what types of properties you want your exception type to support. Choose
appropriate names for these properties. Your exception type must expose a
name property. This is the
only required property.
c03.indd 70c03.indd 70 8/20/07 5:50:39 PM8/20/07 5:50:39 PM
Chapter 3: Built-In and Custom Exception Types
71
Next, extend the functionality of the JavaScript Error type to add support for a static JavaScript
method that encapsulates the logic that instantiates your custom exception type. Follow these steps to
implement this static method:
1. Choose an appropriate name for the method. Use the same name as the name of your exception
type except for two differences: use camel casing instead of Pascal casing, and drop the word

Exception from the end of the name.
2. Decide on how many and what types of parameters you want this method to support. This nor-
mally consists of two sets of parameters. The first set consists of a single string parameter that
contains the error message. The second set contains one parameter for each property of your
custom exception type. In other words, the second set must provide the values for the properties

of your custom exception type.
3. Build a string that contains the values of all the parameters passed into the method.
4. Call the create static function on the JavaScript Error type, passing in two arguments to create
an
Error object. The first argument must contain the string you built in step 3. The second argu-
ment must be a container of the properties that describe your custom exception. This container
is normally an object literal.
5. Call the popStackFrame method on the Error object you created in step 4 to reset the values of
the
fileName and lineNumber properties of the Error object.
6. Return the Error object to the caller of the function.
Using the Recipe
In this section, you use the recipe to develop a custom ASP.NET AJAX exception type. This exception
type is raised when a duplicate item is added to a collection. First you need to pick a name for your
custom exception type that meets the requirements specified in step 1 of the recipe. I think you’ll agree
with me that
DuplicateItemException is an appropriate name for this custom exception type. Follow-
ing step 1 of the recipe, this name uses Pascal casing and ends with the word
Exception . Next, you
need to decide on how many and what types of properties you want the
DuplicateItemException
exception to support. Every exception type in the ASP.NET AJAX client-side framework must expose a

name property; therefore, one of the properties of your custom exception must be the name property. It’s
also a good idea to present the
catch block that will catch your exception with more information about
the duplicated item. So, your exception type should also support a second property named
item that
references the duplicated item. You’re done with the second step of the recipe.
Next you need to extend the JavaScript

Error type to add support for a static method that encapsulates
the logic that instantiates the
DuplicateItemException exception type. According to the recipe, the
name of this method must be the camel-casing version of the exception name. You must also drop the
keyword
Exception from the end of the method name. So, the name of your exception-generating
method should be
duplicateItem .
Following the recipe, the
duplicateItem static method must take two arguments. The first argument
contains the optional exception message. The second argument references the duplicated item. Now, let’s
get down to the implementation of the
duplicateItem static method:
c03.indd 71c03.indd 71 8/20/07 5:50:40 PM8/20/07 5:50:40 PM
Chapter 3: Built-In and Custom Exception Types
72
Error.duplicateItem = function(e, myitem)
{
var a=”Sys.DuplicateItemException: “ +
(e ? e : “Duplicate item!”) + “\n”;
if (myitem)
for (var c in myitem)
a += (c + “: “ + myitem[c] + “\n”);
var f = Error.create(a,
{name: “Sys.DuplicateItemException”,
item: myitem});
f.popStackFrame();
return f;
};
Following the recipe, the duplicateItem method first builds a string that contains the string represen-

tation of all the parameters passed into the method. The first parameter is the optional string that
contains the error message:
var a=”Sys.DuplicateItemException: “ +
(e ? e : “Duplicate item!”) + “\n”;
The second parameter is an object that references the duplicated item. The duplicateItem method iter-
ates through the properties of this object and adds the name and value of each enumerated property to
the string being built:
if (myitem)
for (var c in myitem)
a += (c + “: “ + myitem[c] + “\n”);
Next, the duplicateItem calls the create static method on the JavaScript Error type and passes the
two arguments into it to create a new
Error object. The first argument is the string you just built. The
second argument is the object literal that provides more information about your
Sys.DuplicateItem
Exception
. Note that this object literal defines two properties for your custom exception as expected:
var f = Error.create(a,
{name: “Sys.DuplicateItemException”,
item: myitem});
Next, the duplicateItem calls the popStackFrame function on the newly created Error object to reset
the values of the
fileName and lineNumber properties of the object:
f.popStackFrame();
Now you can use your custom exception in a page as shown in the following code:
<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Transitional//EN”
“ /><html xmlns=” />c03.indd 72c03.indd 72 8/20/07 5:50:41 PM8/20/07 5:50:41 PM

Chapter 3: Built-In and Custom Exception Types
73
<head id=”Head1” runat=”server”>
<title>Untitled Page</title>
<script language=”javascript” type=”text/javascript”>
Error.duplicateItem = function(e,myitem)
{
var a=”Sys.DuplicateItemException: “ + (e ? e : “Duplicate item!”) + “\n”;
if (myitem)
for (var c in myitem)
a += (c + “: “ + myitem[c] + “\n”);
var f = Error.create(a,
{name: “Sys.DuplicateItemException”, item: myitem});
f.popStackFrame();
return f;
};

var products = {};
function validateInput(pname, pcategory, pdistributor)
{
if (products[pname])
{
var err = Error.duplicateItem(“Duplicate item!”,
{name: pname,
category: pcategory,
distributor: pdistributor});
throw err;
}
}


function clickCallback()
{
var name = document.getElementById(“name”);
var category = document.getElementById(“category”);
var distributor = document.getElementById(“distributor”);
try
{
validateInput(name.value, category.value,
distributor.value);
products[name.value] = {name: name.value,
category: category.value,
distributor: distributor.value};
}
catch (e)
{
alert(e.message);
}
}

</script>
</head>
<body>
<form id=”form1” runat=”server”>
<asp:ScriptManager runat=”server” ID=”ScriptManager1”/>
<table style=”background-color:LightGoldenrodYellow;
border-color:Tan; border-width:1px;
color:Black;” cellpadding=”2”>
(continued)
c03.indd 73c03.indd 73 8/20/07 5:50:41 PM8/20/07 5:50:41 PM
Chapter 3: Built-In and Custom Exception Types

74
<tr style=”background-color:Tan; font-weight:bold”>
<th colspan=”2”>Product Description</th>
</tr>
<tr>
<td align=”right”>Name:</td>
<td align=”left”>
<input type=”text” id=”name” />
</td>
</tr>
<tr>
<td align=”right”>Category:</td>
<td align=”left”>
<input type=”text” id=”category” />
</td>
</tr>
<tr>
<td align=”right”>Distributor:</td>
<td align=”left”>
<input type=”text” id=”distributor” />
</td>
</tr>
<tr style=”background-color:PaleGoldenrod”>
<td align=”center” colspan=”2”>
<input type=”button” value=”Add Product”
onclick=”clickCallback()” />
</td>
</tr>
</table>
</form>

</body>
</html>
Figure 3-7 shows what you’ll see in your browser when you access this page. Note that the page consists
of three simple text boxes and a button. This page allows you to add a product with a specified name,
category, and distributor to an internal collection.
Figure 3-7
c03.indd 74c03.indd 74 8/20/07 5:50:41 PM8/20/07 5:50:41 PM
Chapter 3: Built-In and Custom Exception Types
75
If you attempt to add a product with the same name as an existing product, the pop-up message shown
in Figure 3-8 is displayed to warn you that the specified item already exists in the collection. As
Figure 3-8 shows, the warning message also displays the names and values of the duplicate item. The
item features three properties:
name , category , and distributor .
Figure 3-8
Now, let’s walk through the previous code listing.
clickCallback
When the end user clicks the Add Product button, the clickCallback JavaScript function is invoked as
follows:
function clickCallback()
{
var name = document.getElementById(“name”);
var category = document.getElementById(“category”);
var distributor = document.getElementById(“distributor”);
try
{
validateInput(name.value, category.value, distributor.value);
products[name.value] =
{name: name.value,
category: category.value,

distributor: distributor.value};
}
catch (e)
{
alert(e.message);
}
}
This function first retrieves the values that the end user has entered for the name, category, and distribu-
tor of the product being added, and then passes these values to the
validateInput JavaScript function
to ensure that the product with the same name does not already exist in the internal collection:
validateInput(name.value, category.value,
distributor.value);
c03.indd 75c03.indd 75 8/20/07 5:50:43 PM8/20/07 5:50:43 PM
Chapter 3: Built-In and Custom Exception Types
76
Note that the clickCallback function wraps the calls into the validateInput function in a try block
because the
validateInput function could raise an exception.
If the validation succeeds, the
clickCallback function uses the JavaScript object literal representation
to instantiate a new product and adds the product to the internal collection:
products[name.value] = {name: name.value,
category: category.value,
distributor: distributor.value};
If the validation fails, the validateInput function raises a DuplicateItemException exception,
which is then caught by the
clickCallback function in the catch block.
validateInput
The validateInput function takes the name, category, and distributor of the new product as its

arguments as shown in the following code:
function validateInput(pname, pcategory, pdistributor)
{
if (products[pname])
{
var err = Error.duplicateItem(“Duplicate item!”,
{name: pname, category: pcategory,
distributor: pdistributor});
throw err;
}
}
The validateInput function calls the duplicateItem static method on the Error object, passing in
the following parameters to create a new
Error object if the products object already contains an object
with the specified name:
❑ The “Duplicate item!” error message.
❑ The object literal representation of the duplicate product. Notice that this representation exposes
three properties:
name , category , and distributor .
Summary
This chapter provided you with an in-depth coverage of the ASP.NET AJAX built-in exception types. It
then gave you a recipe for building your own custom exception types and showed you how to use the
recipe to implement a custom exception type named
DuplicateItemException .
The ASP.NET AJAX JavaScript base type extensions and exception types are only part of the ASP.NET
AJAX client-side framework. The next chapter discusses two other important parts of this framework:
ASP.NET AJAX JavaScript object-oriented programming (OOP) and type reflection extensions.
c03.indd 76c03.indd 76 8/20/07 5:50:44 PM8/20/07 5:50:44 PM

×