Exception handling in ASP.NET MVC Web Api

A suggestion for exception handling in ASP.NET MVC Web API.

Back to blog

Rick Strahl suggests using a global exception filter to streamline error handling for web api controller methods.

Your controller code throws standard .net exceptions and lets the filter translate them to a HttpStatusResponse with an appropriate status code.

I don’t think this by itself is the best solution because it isn’t very explicit in your controller code what will be returned to the client. You have to know that a) a global exception filter has been registered and b) how the filter maps standard .NET exceptions to HTTP error codes.

The intent of your code is clearer if, wherever possible, it explicitly constructs and returns an error response by throwing a HttpResponseException.

There are overloads for the constructor that let you create content to hold an error message so that the error details are serialized through the same content negotiation and serialization process as any other strongly typed model.

The expression is a little unwieldy but that is easily fixed with a simple extension on HttpRequest to construct a HttpResponseException from a code, format string, and parameters.

The global error filter is still a good idea in-case an unhandled .NET exception escapes from the controller method. The error filter is then a fall back to ensure you are making a ‘best attempt’ to translate .net exceptions to appropriate HTTP response codes.

As you read this far, you should follow me on twitter here.