Exception Handling in Web API (Part 2): Exception Filter (Extended)

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 ?
 

Advertisement

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