His can be achieved by 3 simple steps.
step 1 - Create a class that represents your SOAP fault, Decorate the class with [DataContract] attribute and the properties with [DataMember] attribute.
[DataContract]
public class DivideByZeroFault
{
[DataMember]
public string Error { get; set; }
[DataMember]
public string Details { get; set; }
}
step 2 - In the service data contract, use] FaultContract] attribute to specify which operations can throw which SOAP faults.
[ServiceContract]
public interface IService1
{
[FaultContract(typeof( DivideByZeroFault))]
[OperationContract]
float Divide(int val1,int val2);
}
step 3 -in the service implementation create an instance of the strongly typed SOAP fault and throw it using FaultException<T>
public class Service1 : IService1
{
public float Divide(int val1, int val2)
{
try
{
return val1 / val2;
}
catch (DivideByZeroException ex)
{
DivideByZeroFault divideByZeroFault = new DivideByZeroFault();
divideByZeroFault.Error = ex.Message;
divideByZeroFault.Details = "Denominator cannot be zero";
throw new FaultException< DivideByZeroFault>( divideByZeroFault);
}
}
}
Note : Centralize exception handling in wcf can be achieved by implementing IErrorHandler interface.
Related Post :
No comments:
Post a Comment