C# Programming: Using Generic Factory Classes to Create Generic Exception Handlers

Introduction

Exception handling is termed to be a costly affair and should be used meticulously. It undoubtedly serves as an integral part of our applications, and cannot be sidelined for any reason. The common problem in implementing an Exception handling mechanism is the dependency on the library after we create a provider.This C# tutorial looks at a possibility of switching the providers at ease.

It’s a problem for every developer be it ASP.NET developer or C# developer. Evaluating each provider takes some toll on the development. So let us re-use them.

For e.g. If you start using the Enterprise Library, you can’t just switch your code if you decide to switch the provider.The solution in such cases is to create wrappers around this common piece and abstract the provider. You can use factory classes like shown below and abstract the provider. Then switch providers through a simple config change.

For reference: this article uses Enterprise Library as default provider. The code sample below consists of a Factory Class that facilitates easy pick of an Exception handler through a config change.

To start with create an interface, as shown below.

List down all the methods that you think any Exception handling component would have. For now, let’s start with a single method HandleException which asks for an Exception object and a policy name.


namespace Infrastructure.ExceptionHandling
{
   /// <summary>
   /// IExceptionHandler defines a contract for the Exception Handlers.
   /// </summary>
   public interface IExceptionHandler
   {
       /// <summary>
       /// Handles the specified ex, applying the policy.
       /// </summary>
       /// <param name=”ex”>The ex.</param>
       /// <param name=”policyName”>Name of the policy.</param>
       /// <returns></returns>
       bool HandleException(Exception ex, string policyName);    }
}

Create an Exception handler Factory Class to return an instance of the Exception handler.We need to create as many Exception handlers as we need to switch.The Interface IException handler would drive the exception handlers.


namespace Infrastructure.ExceptionHandling
{
   /// <summary>
   /// creates Exception handler.
   /// </summary>
   /// <typeparam name=”TExceptionHandler”>The type of the Exception handler.</typeparam>
   public class ExceptionHandlerFactory < TExceptionHandler > where TExceptionHandler: IExceptionHandler, new()
   {
       /// <summary>
       /// creates an instance for TClass
       /// </summary>
       /// <returns>instance of TClass</returns>
       public static TExceptionHandler CreateProvider()
       {
           TExceptionHandler instance = new TExceptionHandler ();
              return instance;
       }
   }
}

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read