The Exception Filter implementation mentioned in the Part1 of the article is fairly simple and straightforward. But as you start supporting more and more Exceptions, the Cyclomatic Complexity of the “OnException” method would increase because of the “if” condition nature.
A cleaner implementation of the Filter is shown below using Dictionary.
public class DemoExceptionFilter : ExceptionFilterAttribute { public DemoExceptionFilter() { this.ExceptionDictionary = new Dictionary(); this.ExceptionDictionary.Add(typeof(NotImplementedException), HttpStatusCode.ServiceUnavailable); this.ExceptionDictionary.Add(typeof(ArgumentOutOfRangeException), HttpStatusCode.BadRequest); } public IDictionary ExceptionDictionary { get; private set; } public override void OnException(HttpActionExecutedContext ExecutedContext) { if (ExceptionDictionary.ContainsKey(ExecutedContext.GetType())) { ExecutedContext.Response = new HttpResponseMessage(ExceptionDictionary[ExecutedContext.GetType()]); } else { throw new HttpResponseException( new HttpResponseMessage(HttpStatusCode.InternalServerError)); } base.OnException(ExecutedContext); } }
Isn’t that cleaner ?