There are two ways for a WCF service to support exception handling:
1.Defining the serviceDebug.includeExceptionDetailInFaults attribute to “true” in the hosts .config file
2. Defining the includeExceptionDetailInFaults attribute to “true” on the service class.
Example:
Config File Solution:
<behaviors>
<serviceBehaviors>
<behavior name=”ServiceBehavior”>
<serviceMetadata httpGetEnabled=”true”/>
<serviceDebug includeExceptionDetailInFaults=”true”/>
</behavior>
</serviceBehaviors>
</behaviors>
Attributed Class Solution:
[ServiceBehavior(IncludeExceptionDetailInFaults=true)]
public class CustomersService : ICustomersService
{
private CustomerDetail customerDetail = null;
… etc
Throwing the Exception
Setting the includeExceptionDetailInFaults to true is your first step in supporting exceptions in WCF.
The next step is to have your service throw the FaultException exception (a class in the System.ServiceModel.FaultException namespace).
Note that you cannot expect to simply use the typical Exception class when you wish to throw exceptions from the WCF host to the WCF client.
To throw exceptions over the WCF bindings you will need to use the FaultException class.
Throwing FaultException Example:
try
{
//Try to do stuff
}
catch
{
throw new FaultException(“Full ruckus!”);
}
Catching FaultException Example:
Now the WCF client can catch the FaultException…
try
{
//Client calls services off the proxy
}
catch(FaultException fa)
{
MessageBox.Show(fa.Message);
}
Distinguish Types of Fault Exceptions
The FaultException class is a generic class for WCF exceptions. In order to determine what type of FaultExceptions occur, you use the FaultCode class.
On the WCF service the FaultCode implementation will look something like this:
try
{
//Connect to a database
}
catch
{
throw new FaultException(“Full ruckus!”, new FaultCode(“DBConnection”));
}
On the WCF client, the FaultCode implementation will look something like this:
try
{
//Call services via the proxy
}
catch(FaultException fa)
{
switch(fa.Code.Name)
{
case “DBConnection”:
MessageBox.Show(“Cannot connect to database!”);
break;
default:
MessageBox.Show(“fa.message”);
break;
}
}
for more information you can look here and also here