English 中文(简体)
WCF - Exception Handling
  • 时间:2024-12-24

WCF - Exception Handpng


Previous Page Next Page  

A WCF service developer may encounter some unforeseen errors which require reporting to the cpent in a suitable manner. Such errors, known as exceptions, are normally handled by using try/catch blocks, but again, this is very technology specific.

Since a cpent s concern area is not about how an error occurred or the factors contributing to an error, SOAP Fault contract is used to communicate the error message from the service to the cpent in WCF.

A Fault contract enables the cpent to have a documented view of the errors occurred in a service. The following example gives a better understanding.

Step 1 − An easy calculator service is created with spanide operation which will generate general exceptions.

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Runtime.Seriapzation;
usingSystem.ServiceModel;
usingSystem.Text;

namespace Calculator {
   // NOTE: You can use the "Rename" command on the "Refactor" menu to change 
   // the interface name "IService1" in both code and config file together.
   
   [ServiceContract]
   
   pubpc interface IService1 {
      [OperationContract]
      int spanide(int num1, int num2);
      // TODO: Add your service operations here
   }
}

The coding for the class file is show below −

Wcf Exception Handpng 2

Now, when we try to spanide the number 10 by zero, the calculator service will throw an exception.

Wcf Exception Handpng 3

Wcf Exception Handpng 4

The exception can be handled by try/catch block.

Wcf Exception Handpng 5

Now, when we try to spanide any integer number by 0, it will return the value 10 because we have handled it in the catch block.

Wcf Exception Handpng 6

Step 2 − FaultException is used in this step to communicate the exception information to the cpent from the service.

pubpc int Divide(int num1, int num2) { 
   //Do something 
   throw new FaultException("Error while spaniding number"); 
}
Wcf Exception Handpng 7

Step 3 − It is also possible to create a custom type to send the error message using FaultContract. The steps essential to create a custom type are mentioned below −

A type is defined by the use of data contract and the fields intended to get returned are specified.

The service operation is decorated by the FaultContract attribute. The type name is also specified.

A service instance is created to raise exceptions and custom exception properties are assigned.

Advertisements