Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting exception handled in Web API ExceptionFilterAttribute

Is there any way in ASP.NET Web API to mark an exception as handled in an ExceptionFilterAttribute?

I want to handle the exception at the method level with an exception filter and stop the propagation to a globally registered exception filter.

Filter used on a controller action:

public class MethodExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is NotImplementedException)
        {
            context.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent(context.Exception.Message)
            };
            // here in MVC you could set context.ExceptionHandled = true;
        }
    }
}

The globally registered filter:

public class GlobalExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is SomeOtherException)
        {
            context.Response = new HttpResponseMessage(HttpStatusCode.SomethingElse)
            {
                Content = new StringContent(context.Exception.Message)
            };
        }
    }
}
like image 297
adamwtiko Avatar asked May 08 '13 13:05

adamwtiko


1 Answers

Try throwing an HttpResponseException at the end of your local handling. By design, they are not caught by exception filters.

throw new HttpResponseException(context.Response);
like image 167
Mac Avatar answered Sep 30 '22 17:09

Mac