Exception Handling in ASP.NET Web Api 2

Problem:

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 additional information as the content. Moreover, I need the content to look like a serialized Exception object (has the message , exceptionMessage , stackTrace , ... properties).

Suggested solutions:

  • Create your own exception classes and create a custom exception filter to apply to any controller action. these custom exception filters handle an exception that is thrown according to its type (one of the custom exceptions that I have already defined) and accordingly responds through something like this (filter code):

     context.Response = context.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new Exception("my exception"))); 
  • completion of already written web api 2 *ActionResult classes ( System.Web.Http.Results.UnauthorizedResult Unauthorized() , System.Web.Http.Results.OkResult Ok() , etc.) and adding some user data to them and their use, so that their result is transmitted to the client each time, re the call (the problem in this case, my type of action of the controller action should be IHttpActionResult , which is not so easy to check and read as a strongly typed action).

Which solution to choose? Or is there another way to do what I'm trying to achieve here?

+6
source share
2 answers

Or you can use the built-in, turnkey solution: exception filters .

You might also be interested in exception handling starting with Web API 2.x.

+7
source

From what I understand, you do not want to handle exceptions thrown by the code, but rather create them in your action methods. In the case where exceptions are excluded from other areas of the code (other actions that you call inside your actions or other filters, you can use exception filters or global error handling).

Therefore, I would go with your second approach (although you do not need to tweak the results of actions much). Your code is actually much simpler than unit test with IHttpActionResult, because you can directly check the type of result. In fact, one of the reasons IHttpActionResults adds simplification to unit testing.

The flow of your code is simpler because you do not need to throw to generate errors, and you can always check the contents of ok (returnValue), as you can see below.

 [TestMethod] public void GetProduct_ShouldReturnCorrectProduct() { var testProducts = GetTestProducts(); var controller = new SimpleProductController(testProducts); var result = controller.GetProduct(4) as OkNegotiatedContentResult<Product>; Assert.IsNotNull(result); Assert.AreEqual(testProducts[3].Name, result.Content.Name); } 

http://www.asp.net/web-api/overview/testing-and-debugging/unit-testing-with-aspnet-web-api

+1
source

All Articles