Introduction
This article covers the following areas:
- How to enable/disable sending the exception details from WCF service to client
- How to use faults to throw custom error messages to client
Details
1. How to enable/disable sending the exception details from WCF service to client
If you throw an exception from WCF service, WCF environment automatically converts the exception into FaultException
. The information that the client receives depends on the endpoint behavior. See the following two scenarios:
When Behavior contains <serviceDebug includeExceptionDetailInFaults="False" />:
From the WCF service, throw the exception as shown below:
throw new Exception("Custom Exception");
At client side, you will get FaultException
with message, “The server was unable to process the request due to an internal error…”. In this case, the user will not come to know the exception that has been thrown.
When Behavior contains <serviceDebug includeExceptionDetailInFaults="True" />:
From the WCF service, throw the exception as shown below:
throw new Exception("Custom Exception");
At client side, you will get FaultException
with message “Custom Exception
”.
Note: In production, you have to keep includeExceptionDetailInFaults=”False”
in order to restrict the service from sending sensitive information to client.
2. How to use faults to throw custom error messages to client
From the above, we understood that you can’t throw custom error messages as exceptions from a service. In order to throw custom error messages, you have to define a data contract type and throw that as a fault. See the following example.
Create a data contract as follows:
[DataContract]
public class OrderFault
{
[DataMember]
public int OrderId { get; set; }
[DataMember]
public string Message { get; set; }
}
In order to throw Fault to client, we have to specify the expected faults above the method/operation using the FaultContractAttribute
as follows:
[OperationContract]
[FaultContract(typeof(OrderFault))]
OrderType GetOrder(int orderId);
In the method definition, throw the Fault as follows:
OrderFault fault = new OrderFault{OrderId = 10, Message="Fault"};
throw new FaultException<OrderFault>(fault, "Order Fault");
Now at client side, you have to catch the fault as follows:
catch (FaultException<OrderFault> ex)
{
}
Inside catch
, you can get the exception details using ex.Detail
. In our case, it's OrderFault
.
That’s it. In this way, you can throw custom error message as fault from WCF service and use in client.
Note: Even if you throw fault from operation, if you don’t specify the expected Fault for the operation, at client side you will not get the fault.
History