Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

throw of HttpResponseException not getting caught by ExceptionFilterAttribute

I have a class:

public class ApiExceptionFilterAttribute : ExceptionFilterAttribute,IExceptionFilter
{        public override void OnException(HttpActionExecutedContext context)
    {
        // ... etc...
    }
}

... which I have registered in global.asax.cs thus:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        var exceptionFilter = new ApiExceptionFilterAttribute();

        GlobalConfiguration.Configuration.Filters.Add(exceptionFilter);

    }
}

My application throws exceptions in various ways, and in most cases, I can see that the OnException method is being invoked as expected. However, if my Web Api controller method throws a HttpResponseException, it seems to be bypassing the exception filter. I get a response returned as expected, but it isn't because of anything the exception filter is doing (the OnException method is not being called).

What is going on to cause this "selective" behavior for my exception filter? How can I ensure that OnException will be called for ALL exceptions thrown from within controller methods?

like image 945
Carl R. Avatar asked Sep 18 '25 10:09

Carl R.


1 Answers

This is because HttpResponseException is caught by IHttpActionInvoker internally and create HttpResponseMessage; hence this special exception can't be caught.

like image 177
stevanuz Avatar answered Sep 21 '25 00:09

stevanuz