Tuesday, October 28, 2014

Exception Handling in Web API 2

When working with Web API 2, unhandled exceptions thrown by controllers are returned to the client as web HTTP status code 500 (Internal Server Error).  An exception filter can be used to replace this generic error with something a little more meaningful.  Another benefit to using exception filter is that it centralizes exception handling.  This means that the most of the time you will not need a try catch statement in your controller methods. Exception filters will catch any exceptions thrown by a controller method that is not an HttpResponseException.

For debugging purposes I decided I wanted to return the entire exception message in my response. For release I have several exception filters targeted to specific exceptions that return meaningful messages to the client. 

To create an exception filter, derive from System.Web.Http.Filters.ExceptionFilterAttribute class and override the OnException method.

Exception filters can be applied as an attribute to the entire controller class, to individual methods, or registered globally in the WebApiConfig.  I registered mine with the debug compiler switch to ensure that this particular exception filter is not used when compiled for release.

One more thing to consider is the status code your sending back with the exception. Sending back the correct exception is important to help the client determine what has gone wrong.  Brockallen has a nice guide for which HTTP status code to use on his blog

This takes care of the majority of error that are a concern when building out a Web API solution, however there are still exceptions that will not be caught by exception filters. That is where Web API Global Error Handling comes into play.

No comments:

Post a Comment