• Aucun résultat trouvé

Handling Errors in the Asynchronous Process

Dans le document Ajax with ASP.NET (Page 166-169)

#region ICallbackEventHandler Members public string GetCallbackResult() {

return “Server method completed at: “ + DateTime.Now.ToLongTimeString();

}

public void RaiseCallbackEvent(string eventArgument) {

System.Threading.Thread.Sleep(2000);

}

#endregion }

So, now you have a fully functional, albeit very simple, implementation of Asynchronous Client Script Callbacks. The server-side methods in this example are extremely simple and would not normally have any problems or generate any exceptions, but in a normal application where complexity is much higher, this is a very real consideration. Luckily, the asynchronous client script framework provides a mecha-nism for handling this.

Handling Errors in the Asynchronous Process

When an error occurs on the server, this usually means an exception has been thrown. Obviously, some way of identifying when an exception has occurred and dealing with this on the client browser is required. In the same way that you defined a JavaScript method that is called on completion of the asyn-chronous process, you can define a JavaScript method that is called when an exception is raised on the server during your asynchronous callback. This is specified as an additional parameter in the call to the GetCallbackEventReferencemethod, which is shown in the following example:

string js = Page.ClientScript.GetCallbackEventReference(this,

“arg”, “OnServerCallComplete”, “ctx”,”OnServerCallError”, true);

The parameter that contains OnServerCallErroridentifies the name of the JavaScript method that is called when an exception occurs on the server. The number of parameters that this method requires is

141

What Is Built into ASP.NET

almost identical to the method defined previously to cater for a successful call. The JavaScript imple-mentation for the OnServerCallErrormethod is shown here:

function OnServerCallError(err,ctx) {

alert(“An error occurred! [“ + err + “] Context passed in was [“ + ctx + “]”);

}

The first parameter errrepresents the message of the exception that was generated, and the ctx param-eter represents the same context defined in previous examples.

To demonstrate this, the implementations of the server-side methods have been altered to explicitly throw an exception in order to simulate an error condition. In the following example, the

GetCallbackResultmethod has been modified to throw an exception:

public string GetCallbackResult() {

throw new Exception(“Whoa! This is a server side exception from

‘GetCallbackResult’”);

return “Server method completed at: “ + DateTime.Now.ToLongTimeString();

}

This time, when the button on the web page is clicked, the asynchronous process is initiated as expected.

However, the JavaScript error routine is now invoked, with the exception message being displayed, along with the context data you defined earlier. This, the definition of JavaScript handler methods for both a successful and an unsuccessful call, would typically be basic requirements for any production system using the Asynchronous Client Script Callback techniques.

Although the preceding code example allows an exception to be handled by the browser for the purpose of demonstration, it is important that you properly handle all exceptions in your callback code. Normal exception-handling techniques should be used with a try...catchsyntax. This way, only exceptions that are meant to be flowed and handled by the browser are allowed by your code. In addition, your server- side code can take action to prevent data corruption or undesired behavior before allowing the exception to be passed up to the client-side code.

In the preceding example, the exception was generated from the GetCallbackResultmethod. The JavaScript error handler method displayed the message of the exception as expected, but what if the excep-tion were generated by the companion RaiseCallbackEventserver-side method? In the following exam-ple, the generation of the exception has been moved to the RaiseCallbackEventmethod and removed from the GetCallbackResultmethod. To aid this example and prevent confusion, the entire server-side code listing is shown:

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

142

Chapter 6

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Text;

public partial class

GetCallbackEventWithErrorHandlingExample_GetCallbackEventWithErrorHandlingExample : System.Web.UI.Page, ICallbackEventHandler

{

protected void Page_Load(object sender, EventArgs e) {

// Get our callback event reference

string js = Page.ClientScript.GetCallbackEventReference(this,

“arg”, “OnServerCallComplete”, “ctx”,”OnServerCallError”, true);

// Create a simplified wrapper method

StringBuilder newFunction = new StringBuilder();

newFunction.Append(“function StartAsyncCall(arg, ctx) “);

newFunction.Append(“{ “);

newFunction.Append(js);

newFunction.Append(“ } “);

// Now register it

Page.ClientScript.RegisterClientScriptBlock(this.GetType(),

“NewAsyncMethod”,

newFunction.ToString(), true);

}

#region ICallbackEventHandler Members public string GetCallbackResult() {

return “Server method completed at: “ + DateTime.Now.ToLongTimeString();

}

public void RaiseCallbackEvent(string eventArgument) {

System.Threading.Thread.Sleep(2000);

throw new Exception(“Whoa! This is a server side exception from

‘RaiseCallbackResult’”);

}

#endregion }

The results from this are not what you might expect and are shown in Figure 6-3.

Figure 6-3

143

What Is Built into ASP.NET

Here you can see that the exception message has been displayed, in addition to the result of the GetCallbackResultmethod. Both of the messages have been aggregated together, but separated by a pipe (|) character. What is happening is that the asynchronous client script framework is still calling both of the required methods of the ICallbackEventHandlerinterface, even though one of the meth-ods generated an exception. The fact that one of the methmeth-ods generates an exception does not preclude the execution of the other method. This is an important point because the GetCallbackResultmethod needs to be aware of any errors that have occurred during the execution of the RaiseCallbackEvent method and not blindly execute assuming that if execution reaches that method, then all previous pro-gram execution has occurred without error.

Dans le document Ajax with ASP.NET (Page 166-169)

Documents relatifs