WCF service unhandled exception handling
When an exception occurs in a WCF service, it is handled automatically by the framework and the client channel is terminated. This is the default behaviour.
But how to catch the exceptions without try-catch blocks in each and every service method?
The solution is to implement the IErrorHandler interface and make it your service’s service behavior. Typically we just want to know what exception was thrown and perhaps log it somewhere. At least, that was what I needed. What follows is a super-minimal but complete example:
There are two steps. First, implement an ErrorHandlerAttribute -class:
The code above just traces the exception but you may want to modify the generated exception to the client etc.
public class ErrorHandlerAttribute : Attribute, IErrorHandler, IServiceBehavior
{
public ErrorHandlerAttribute()
{
}
public bool HandleError(Exception error)
{
Trace.TraceInformation("Unhandled exception occured: {0}\nStack trace:\n{1}\nSource\n{2}", error.Message, error.StackTrace, error.Source);
return false;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
fault = null;
}
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher disp in serviceHostBase.ChannelDispatchers)
{
disp.ErrorHandlers.Add(this);
}
}
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
}
To enable the Errorhandler in your service class, just use it as an attribute as follows:
[ErrorHandler]
public class ClientConnectionService : IClientConnection
{
// ...
}