My task was to create exception handler on some system that has multiple types of database and big business behavior.
At first, I had done a switch/case that handled the exceptions by type using the Object.GetType() method. After some additional thought, I realized that the types of exceptions are endless --- which meant that, every time a new error is thrown, I would have to add more logic to the switch/case. That will make the switch/case so ugly.
So, I have done it by this way. I need your help if i can improve it more or do I need to change the implementation? Also, where are the weaknesses of this implementation?
IExceptionHandlerFactory
private readonly IHttpContextAccessor HttpContext;
private readonly ILogManager LogManager;
private Dictionary<ExceptionsType, Func<ExceptionHandler>> EntityTypeMapper =
new Dictionary<ExceptionsType, Func<ExceptionHandler>>();
public ExceptionHandlerFactory(IHttpContextAccessor httpContext, ILogManager logManager)
{
HttpContext = httpContext;
LogManager = logManager;
EntityTypeMapper.Add(ExceptionsType.EFException, () =>
{ return new EFExceptionHandler(HttpContext, LogManager); });
EntityTypeMapper.Add(ExceptionsType.Exception, () =>
{ return new GenericExceptionHandler(HttpContext, LogManager); });
EntityTypeMapper.Add(ExceptionsType.OracleException, () =>
{ return new OracleExceptionHandler(HttpContext, LogManager); });
}
public ExceptionHandler GetExceptionHandlerBasedOnType(ExceptionsType type)
{
return EntityTypeMapper[type]();
}
ExceptionHandler
public abstract class ExceptionHandler : Exception
{
private readonly ILogManager LogManager;
public ExceptionsType ExceptionsType { get; set; }
public abstract void Handle(Exception exception);
public ExceptionHandler(ILogManager logManager)
{
LogManager = logManager;
}
public void AddLogForException<T>(
T exception,
IHttpContextAccessor httpContext,
string description)
where T : Exception
{
LogManager.AddLog()
}
}
GenericExceptionHandler
public class GenericExceptionHandler : ExceptionHandler
{
private readonly IHttpContextAccessor httpContext;
public ILogManager LogManager { get; }
public GenericExceptionHandler(
IHttpContextAccessor httpContext,
ILogManager logManager) : base(logManager)
{
this.httpContext = httpContext;
}
public override void Handle(Exception exception)
{
AddLogForException(exception, httpContext, string.Empty);
}
}