WCF Faults
See MSDN P&P Exception Management, MSDN Specifying and Handling Faults in Contracts and Services
FaultContract / FaultException
- Add a [FaultContract(typeof(DivideByZeroException))] for types of faults that may be raised
- Throw a untyped FaultException or
throw new FaultException<DivideByZeroException>(new DivideByZeroException());- If you throw a faultException the service doesn't enter a faulted state
- you can also throw new FaultException<string>("Opps");
Client Exception Handling
using
blocks with clients. Either use the above or write a partial class for the client with an explicit Dispose implementation (see below).A WCF client can use faultException.Detail for a typed faultException.
Or: subscribe the client Faulted event.
Then rebuild the client (new Client())
client.Abort() as your client may throw on Close/Dispose when it is faulted
//don't do using for ClientBase
var client = new CalculatorClient();
try
{
var result = client.Add(1, 10);
//close can throw exceptions!
//and will if(client.State == CommunicationState.Faulted)
client.Close();
total = result.Total;
}
//catch typed exceptions
catch (FaultException<DivideByZeroException> exception)
{
var inner = exception.Detail;
client.Abort();
throw inner;
}
//catch untyped exception
catch (FaultException)
{
client.Abort();
throw;
}
//catch any other general error
catch (CommunicationException)
{
client.Abort();
}
//catch a timeout (slow connection)
catch (TimeoutException)
{
client.Abort();
}
Safe disposable client
Do a partial class. See also: Stack Overflow
public partial class Client : IDisposable
{
void IDisposable.Dispose()
{
if (State == CommunicationState.Faulted)
{
Abort();
}
else
{
Close();
}
}
}
Normal exceptions
IncludeExceptionDetailInFaults="True". Actually it returns a FaultException(typeof(ExceptionDetail)) but does not use a wsdl FaultContract
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
ServiceContract code:
#if DEBUG
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
#endif
Logging and handling exceptions:
- Implement IErrorHandler to log (HandleError) and/or wrap (ProvideError) exceptions
- Subscribe to serviceHost.Faulted event.