Handling Web Service Errors

For simplicity, the previous HTML files have assumed that the web service methods are always successful. As you have learned, however, there are often times when a web service encounters an error and generates an exception. In such cases, the JavaScript code within the OnResult function must test for an error using the error object.

In Chapter 2, you created the ExceptionDemo web service that provides two methods:

string Good() string Bad()

The Good method returns a character string that contains a quote to the caller. In contrast, the Bad method generates an exception.

The following HTML file, CatchError.html, displays a form that contains two buttons. When the user clicks the Good button, the JavaScript code will call the ExceptionDemo web service Good method, displaying the result in the form. If the user clicks the Bad button, the script will call the Bad method that results in an exception. The code, in turn, will display the Exception message within the form as shown in Figure 3.8. Listing 3.7 implements the CatchError.html file.

click to expand
Figure 3.8: Capturing an exception using the JavaScript error object

Listing 3.7 CatchError.html

start example
<html > <head>   <title>Catch Error</title>   <script language="JavaScript">   function InitializeService()   {     service.useService("http://localhost//ExceptionDemo/Service1.asmx?wsdl", Ä "ExDemo");   }   function CallGood()   {         service.ExDemo.callService("Good");   }   function CallBad()   {         service.ExDemo.callService("Bad");   }   function ShowResult()   {      if (event.result.error)        document.DemoForm.BoxText.value = Ä       event.result.errorDetail.string;      else        document.DemoForm.BoxText.value = event.result.value;   }   </script> </head> <body    onload="InitializeService()"           style="behavior:url(webservice.htc)"          onresult="ShowResult()"> <form name="DemoForm">    <button onclick="CallGood()">Good</button>    <button onclick="CallBad()">Bad</button><br>    <textarea name="BoxText" Rows="5" Cols="60"></textarea> </form> </body> </html>
end example

Within the ShowResult function, the code examines the value of the event.result.error attribute. If the attribute is true, an error occurred and the code displays a string that contains a description of the error. If the error attribute is false, the code displays the value returned by the web service:

  function ShowResult()   {      if (event.result.error)        document.DemoForm.BoxText.value = Ä       event.result.errorDetail.string;      else        document.DemoForm.BoxText.value = event.result.value;   }




. NET Web Services Solutions
.NET Web Services Solutions
ISBN: 0782141722
EAN: 2147483647
Year: 2005
Pages: 161
Authors: Kris Jamsa

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net