I wanted a method which caught all unhandled exceptions in my asp.net web api project. I found this post: How do I log ALL exceptions globally for a C# MVC4 WebAPI app? which talks about using ExceptionFilterAttribute and OnException.
This is working so far, that i am able to catch an exception thrown in an api controller, and then identify the exception. I would then like to throw a HttpResponseException with StatusCode and Content specific to the original exception i caught. How would i do this?
This is what i have so far:
public override void OnException(HttpActionExecutedContext context) {
HttpResponseMessage msg = new HttpResponseMessage();
if (context.Exception.GetType() == typeof(DBAccess.DeleteNotAllowed)) {
msg.StatusCode = HttpStatusCode.Forbidden;
msg.Content = new StringContent("Illegal action");
msg.ReasonPhrase = "Exception";
throw new HttpResponseException(msg);
} else {
//handle next exception type
}
}
When a DeleteNotAllowed exception is thrown it is caught as intended and it's error message is sent to the client. However, another exception is thrown at the else statement.