Skip to content

WCF service unhandled exception handling

July 24, 2010

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

{

 // ...

}
About these ads

From → .NET, C#, SOA, Uncategorized, WCF

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: