Best practice for error handling with ASP.NET Web API Best practice for error handling with ASP.NET Web API asp.net asp.net

Best practice for error handling with ASP.NET Web API


Error handling in Web API is considered a cross-cutting concern and should be placed somewhere else in the pipeline so the developers doesn’t need to focus on cross-cutting concerns.

You should take a read of Exception Handling in ASP.NET Web API

What happens if a Web API controller throws an uncaught exception? By default, most exceptions are translated into an HTTP response with status code 500, Internal Server Error.

and also Global Error Handling in ASP.NET Web API 2

You should try to keep your controller lean as much as possible. Error handling like your original code will only result in duplication of code, and unnecessary concerns for the developers to be aware of. Developers should focus on the core-concern, not the cross-cutting concerns. By just focusing on the core-concern the above code will look like this:

[MyAuthentication][MyValidateModel]public Vb.Order PostOrderItem(Vb.Order order){        return Vb.Document.Generate(order);}

Why so lean?

Because :

if (OAuth.isValid(Request.Headers.GetValues("Token").Single()) != true){    HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);    throw new HttpResponseException(httpResponseMessage);}

can be moved into Authentication Filters in ASP.NET Web API 2 that can be applied locally on the controller/action or globally to return a relevant response.

Model Validation in ASP.NET Web API like this

if (!ModelState.IsValid){    HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);    throw new HttpResponseException(httpResponseMessage);}

Can also be moved into a filter like : .

public class MyValidateModelAttribute : ActionFilterAttribute{    public override void OnActionExecuting(HttpActionContext actionContext)    {        if (!actionContext.ModelState.IsValid)        {            actionContext.Response = actionContext.Request.CreateErrorResponse(                HttpStatusCode.BadRequest, actionContext.ModelState);        }    }}


Please refer to this link Exception Handling in ASP.NET Web API - A Guided Tour. There are 4 level exception handling pipeline:

  • Level 1 - HttpResponseException
  • Level 2 - Exception Filters
  • Level 3 - Logging
  • Level 4 - Exception Handlers

Web API provides us a great deal of flexibility in terms of exception handling. To recap:

  • Use HttpResponseException or the shortcut methods to deal with unhandled exceptions at the action level.
  • Use Exception Filters to deal with particular unhandled exceptions on multiple actions and controllers.
  • Use ExceptionLogger to log any unhandled exception.
  • Use Exception Handlers (one per application) to deal with any unhandled exception application-wide.


There are a number of methods, each one step further up the logical object graph;

This article lists them all;http://www.codeproject.com/Articles/850062/Exception-handling-in-ASP-NET-MVC-methods-explaine

I find it useful to use one of the higher level methods in order to avoid duplicate code.