PM's Blog

Pramod Mohanan's notes about ASP.NET, MVC, C#, SQL, jQuery, Bootstrap

Global Error Handler in WCF

I recently read about the First Chance Exception and thought it was quite an interesting. While First Chance Expection helps during debug, for a production scenario we normally need to rely on catching errors using try catch. In a recent WCF project I tried implementing a GlobalErrorHandler and believe me it works like Magic. It takes away a lot of manual effort and logic for handling errors and on top of it does some bits of work like(logging) async so the service user need not wait. It also catches known errors that we may throw across the application and exception that occur during runtime. Pretty cool, huh?

Here is how I achieved it

Step 1 – Create a BehaviourAttribute

Create a BehaviourAttribute implementing System.Attribute class and implementing IServiceBehaviour interface like this.

public class GlobalErrorHandlerBehaviourAttribute : Attribute, IServiceBehavior
{
  private readonly Type _errorHandlerType;
 
  public GlobalErrorHandlerBehaviourAttribute(Type errorHanlderType)
  {
    _errorHandlerType = errorHanlderType;
  }
 
  public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
  {
  }
 
  public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
  {
    var handler = (IErrorHandler) Activator.CreateInstance(this._errorHandlerType);
    foreach (var channelDispacherBase in serviceHostBase.ChannelDispatchers)
    {
      var channelDispatcher = channelDispacherBase as ChannelDispatcher;
      if(channelDispatcher != null)
        channelDispatcher.ErrorHandlers.Add(handler);
    }
  }
 
  public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
  {
  }
}

Step 2 – GlobalErrorHandler class

Create class GlobalErrorHandler implementing the interface IErrorHandler

public class GlobalErrorHandler : IErrorHandler
{
  public bool HandleError(Exception error) //this runs async
  {
    //add your logic to check the error and log to db or log files etc.
    return true;
  }
 
  public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
  {
    //check the error here and return the 'fault' object with message that you want the user to see
  }
}

Step 3 – Using the Attribute

[GlobalErrorHandlerBehaviour(typeof(GlobalErrorHandler))]
public class MyService : IMyService
{
  // implement service methods here
}

That’s it, all errors caught can then be handled at one place also can be logged/written to db etc. async. Isnt that fantastic?

Updated: September 3, 2015 — 10:39 am

Leave a Reply

Your email address will not be published. Required fields are marked *

PM's Blog © 2018