Use ASP. Net ajax to asynchronously call the class methods in Web Services and pages (2): handle exceptions in asynchronous calls

Source: Internet
Author: User
This article is from ASP.. Net Ajax programming Chapter II: client-related Microsoft Ajax library Chapter III asynchronous call of Web Services and class methods on pages. For more information, see other articles in this chapter.

3.3Handle exceptions in asynchronous calls

In traditional Web ApplicationsProgramThe exception handling process is relatively simple-even if the developer does not perform any processing, the browser displays the exception information by default in the browser. For Ajax applications, things are not that simple. The "Asynchronous" nature of Ajax programs, coupled with the running behavior in the background, makes it difficult for users and even developers to determine whether a call to the server is successfully completed, the browser is naturally powerless to handle exceptions that occur when Ajax is running.

In the first two sections of this chapter, Asp. with the help of the net Ajax asynchronous communication layer, we have been able to easily initiate asynchronous HTTP requests from the client to the server-in ideal cases, this will naturally not be a problem and is enough to use. However, there will be a lot of uncertainty in the running of web programs. From the unstable network conditions to developers' carelessness, any unpredictable problem will lead to the failure of an asynchronous call.

Therefore, in the implementation of ASP. NET Ajax asynchronous communication layer, an exception handling method is also built-in. Do you still remember the syntax used to call Web Service proxy on the client?

 
[Namespace]. [classname]. [methodname] (param1, param2 ..., Callbackfunction)

After successfully calling the callback function callbackfunction, we can also provide another callback function that fails to be called. In this way, the syntax for the client to call the Web Service proxy is changed:

 
[Namespace]. [classname]. [methodname] (param1, param2 ..., Onsucceeded, onfailed)

Note the newly added onfailed callback function in bold. This function will be called by the ASP. NET Ajax asynchronous communication layer when an exception occurs in this asynchronous communication. The onsucceeded action will not be affected and will still be executed after the call is successful.

The onfailed callback function accepts a parameter of the type SYS. net. webserviceerror, indicating the exception object. The function signature is similar to the following:

 
Function onfailed (error ){
 
// Obtain and handle exception information
 
}

The sys. net. webserviceerror type of ASP. NET Ajax client encapsulates exceptions that may occur when an asynchronous request server is sent. It provides several read-only attributes and a detailed description of the exception information. The attributes of the SYS. net. webserviceerror type are shown in Table 3-1.

Table 3-1 attributes of the SYS. net. webserviceerror type

    1. Attribute name: Description
    2. Exceptiontype: gets the specific types of server exceptions.
    3. Message: Get detailed exception description
    4. Statuscode: gets the status code of the HTTP response that causes an exception
    5. Stacktrace: gets stack trace information for server exceptions.
    6. Timedout: returns a Boolean value, indicating whether the exception is caused by network connection timeout.

Note: According to the naming rules of ASP. NET Ajax client components, you must prefix "GET _" or "SET _" before the attribute names. For example, if you want to obtain the value of the message attribute of a sys. net. webserviceerror type exception, you should follow the following method:Code:

 
VaRErrormessage = errorobj. get_message ();

Let's use a simple example program to demonstrate how to handle exceptions when the client calls the Web Service proxy, and how to use each attribute of the SYS. net. webserviceerror type.

The example program is a division calculator. The program uses ASP. net Ajax asynchronous communication layer sends the input divisor and divisor to the server. After the server completes the trigger computation process, the result is returned to the client for display. The initial interface for running the program is shown in 3-4.

Figure 3-4 initial interface of the Division Calculator

Enter the divisor and divisor, and then click the question mark ("?"). The program will call the server-side web service to complete the division and display the operator in the question mark button, as shown in Figure 3-5.

Figure 3-5 execute a common division

If the input divisor is 0, an exception is thrown during execution on the server. We will not process this exception on the server side, so this asynchronous call will fail, and the client will also display detailed information about the exception. See Figure 3-6.

Figure 3-6 Division failure due to Division 0

Let's start with the Web service on the server. We name the Web Service mathservice and define a method named divide () in it to perform Division operations. The divide () method accepts two parameters, namely divisor and divisor. The logic is very simple. The Code is as follows:

 
[WebService (namespace ="Http://tempuri.org /")]
 
[Webservicebinding (conformsto = wsiprofiles. basicprofile1_1)]
 
[Scriptservice]
Public ClassMathservice: system. Web. Services. WebService
 
{
 
[Webmethod]
 
Public IntDivide (IntA,IntB)
 
{
 
Return(Int) (A/B );
 
}
 
}

It is necessary to remind you again that the [scriptservice] attribute must be added to the web service class, the method to be exposed to the client must also add the [webmethod] Attribute-these are necessary conditions for allowing the Web Service proxy to be called from the client.

On the ASP. NET page, add the scriptmanager control and reference of the preceding Web Service:

<ASP: scriptmanager ID= "SM" Runat= "Server">
 
<Services>
 
<ASP: servicereference Path= "Services/mathservice. asmx" />
 
</Services>
 
</ASP: scriptmanager>

Then define the program interface on the ASP. NET page:

<Input ID= "Guid" Type= "Text" Style= "Width: 40px" />/
 
<Input ID= "TBB" Type= "Text" Style= "Width: 40px" />=
 
<Input ID= "Btninvoke" Type= "Button" Value= "? " 
Onclick= "Return btninvoke_onclick ()" />
 
<Div ID= "Result"> </Div>

The first two are <input/> (IDs are DSPs and TBB) used to allow users to enter the divisor and divisor, and the third is <input/> (ID is btninvoke) the button (type = "button") is used to trigger the call to the Web service on the server, and the operator after division is complete is displayed; the <DIV/> with the ID result below is used to display possible exception information.

 
FunctionBtninvoke_onclick (){
 
VaRA = $ get ("Guid"). Value;
 
VaRB = $ get ("TBB"). Value;
Mathservice. Divide (a, B, onsucceeded, onfailed );
 
}

Note that the bold part is the line that calls the Web service client proxy. The callback function onsucceeded after successful call and onfailed when the call fails are passed in.

The callback function onsucceeded () for successful calls is relatively simple. It is not mentioned here:

 
Function onsucceeded (result ){
 
$ Get ("Btninvoke").Value= Result;
 
 
 
$ Get ("Result"). Innerhtml ="";
 
}

The onfailed () callback function is the focus of this example program:

 
FunctionOnfailed (error ){
 
 
 
// Obtain exception information
VaRStacktrace = Error. get_stacktrace ();
 
VaRMessage = Error. get_message ();
 
VaRStatuscode = Error. get_statuscode ();
 
VaRExceptiontype = Error. get_exceptiontype ();
 
VaRTimeout = Error. get_timedout ();
 
 
 
// Display exception information
 
$ Get ("Result"). Innerhtml =
 
"<Strong> stack trace: </strong>"+ Stacktrace +"<Br/>"+
"<Strong> service error: </strong>"+ Message +"<Br/>"+
 
"<Strong> Status Code: </strong>"+ Statuscode +"<Br/>"+
 
"<Strong> exception type: </strong>"+ Predictiontype +"<Br/>"+
 
"<Strong> is Timeout: </strong>"+ Timeout;
 
 
 
$ Get ("Btninvoke"). Value ="? ";
 
}

As you can see, the onfailed () function first obtains the attributes of the passed SYS. net. webserviceerror object, and then displays them in <DIV/> with the ID as result.

This completes the compilation of the sample program. Run the program and try to do some division. If the program is correctly written, you will see the interfaces 3-4, 3-5, and 3-6.

of course, the purpose of this example program is to demonstrate how to handle exceptions when calling the Web service on the server side. Therefore, the exception information is not explicitly displayed. In actual development, we should not completely display such abrupt exception details. The common practice is to handle different exceptions and display friendly prompts to users as needed.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.