.NET can make it easy to forget that you are calling a web service. When you deal with proxy classes, you often get used to working with a web service as if it were no different than any other method. However, this can be dangerous. Web methods are different. One big difference is the way in which you throw exceptions from a web service. The following sections explore how to throw exceptions. Creating a Web Service ExceptionFortunately, the SOAP specification describes how an exception is thrown over the Web through this protocol. These exceptions can be business logic exceptions or those generated by .NET when processing a call. The important point is that if you wrap these exceptions appropriately, the client should be able to understand how to manage them. .NET provides the SoapException object for wrapping an exception for SOAP transmission. This class has a number of parameters that you may not be used to working with when throwing exceptions. The parameters and properties include the following:
Listing 16.6 shows a new version of the GetCustomerProfile web method. This version checks to see whether the customer exists. If not, it throws a SoapException with the Code property set to ClientFaultCode. Listing 16.6. Creating a SOAP Exception
Handling a Web Service ExceptionYou handle the SOAP exception by catching it the same way you might catch any other .NET exception. You can use the .NET SoapException class for this purpose. .NET will automatically translate the SOAP exception into this object for your use. The following simple example shows how to catch the exception and display it in a message box. We added this code to our Windows form example. } catch (System.Web.Services.Protocols.SoapException ex) { string msg = "Message: " + ex.Message + ", Actor: " + ex.Actor + ", Fault Code: " + ex.Code.ToString(); MessageBox.Show(msg); } |