WCF provides FaultException class that can be used to send exception details to client.
1. Through Exception class object from service
2. Using default FaultException
Through Default FaultException class object from service
<serviceDebug includeExceptionDetailInFaults="true"/>
3. Through Custom class object (Fault contract) using FaultException class
Service Code:
1. Through Exception class object from service
<serviceDebug includeExceptionDetailInFaults="false"/>
2. Using default FaultException
throw new FaultException(ex.Message);
OR
Enable includeExceptionDetailInFaults in config<serviceDebug includeExceptionDetailInFaults="true"/>
3. Through Custom class object (Fault contract) using FaultException class
Service Code:
[ServiceContract]
public interface IService1
{
[OperationContract]
[FaultContract(typeof(ClsCustomException))]
int CalculateCost(string itemCount);
}
[DataContract]
public class ClsCustomException
{
[DataMember]
public string Message { get; set; }
[DataMember]
public string Description { get; set; }
[DataMember]
public string StackTrace { get; set; }
}
public int CalculateCost(string itemCount)
{
try
{
return int.Parse(itemCount) * 120;
}
catch (Exception ex)
{
//Without
fault exception
//throw
ex;
//Simple
fault exception sending message only to client side
//throw
new FaultException(ex.Message);
//Fault
contract (using our custom class to send details of exception to client)
ClsCustomException objMyException = new ClsCustomException();
objMyException.Message =
ex.Message;
objMyException.Description = "Error in itemCount conversion to int";
objMyException.StackTrace =
ex.StackTrace;
throw new FaultException<ClsCustomException>(objMyException);
}
}
Client Code:
static void Main(string[] args)
{
ServiceReference1.Service1Client _client
= new
ServiceReference1.Service1Client();
try
{
Console.WriteLine("Enter
number...");
Console.WriteLine( _client.CalculateCost(Console.ReadLine()));
Console.ReadLine();
}
catch (FaultException<ServiceReference1.ClsCustomException> ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.Detail.Description);
Console.WriteLine(ex.Detail.StackTrace);
Console.ReadLine();
}
}








