title: Exception Handling in ASP.NET Web Api 2
body: <p><strong>Problem:</strong></p>
  
  <p>I need to handle web api 2 exceptions and return a rich object with the correct status code (401 for Unauthorized, 404 for ContentNotFound, etc) and some extra information as the content. Moreover, I need the content to look like a serialized <code>Exception</code> object (have the <code>message</code>, <code>exceptionMessage</code>, <code>stackTrace</code>, ... properties).</p>
  
  <p><strong>Suggested Solutions:</strong></p>
  
  <ol>
  <li><p>Create custom exception classes and writing a custom exception filter to apply to any controller's action. this custom exception filters handles the exception thrown according to it's type (one of the custom exceptions that I've already defined) and responds accordingly via something like this (filter's code):</p>
  
  <pre><code>context.Response = context.Request.CreateErrorResponse(HttpStatusCode.Unauthorized,
                                      new Exception("my exception")));
  </code></pre></li>
  <li><p>wrapping the already written web api 2 <code>*ActionResult</code> classes ( <code>System.Web.Http.Results.UnauthorizedResult Unauthorized()</code>, <code>System.Web.Http.Results.OkResult Ok()</code>, etc ) and adding some custom data to them and use them so that their result get passed to client every time they're called (the problem is in this case my controller's action's return type should be <code>IHttpActionResult</code> which is not as easily testable and readable as a strongly typed action).</p></li>
  </ol>
  
  <p>What solution should I choose? Or is there any other way to do what I'm trying to achieve here?</p>