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 extra information as the content. Moreover, I need the content to look like a serialized Exception
object (have the message
, exceptionMessage
, stackTrace
, ... properties).
Suggested Solutions:
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):
context.Response = context.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new Exception("my exception")));
wrapping the already written web api 2
*ActionResult
classes (System.Web.Http.Results.UnauthorizedResult Unauthorized()
,System.Web.Http.Results.OkResult Ok()
, 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 beIHttpActionResult
which is not as easily testable and readable as a strongly typed action).
What solution should I choose? Or is there any other way to do what I'm trying to achieve here?