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
usingblocks 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();
var result = client.Add(1, 10);
//close can throw exceptions!
//and will if(client.State == CommunicationState.Faulted)
total = result.Total;
//catch typed exceptions
catch (FaultException<DivideByZeroException> exception)
var inner = exception.Detail;
//catch untyped exception
//catch any other general error
//catch a timeout (slow connection)
Safe disposable client
Do a partial class. See also: Stack Overflow
public partial class Client : IDisposable
if (State == CommunicationState.Faulted)
IncludeExceptionDetailInFaults="True". Actually it returns a FaultException(typeof(ExceptionDetail)) but does not use a wsdl FaultContract
<serviceDebug includeExceptionDetailInFaults="true" />
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
Logging and handling exceptions:
- Implement IErrorHandler to log (HandleError) and/or wrap (ProvideError) exceptions
- Subscribe to serviceHost.Faulted event.