Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Exception Filter not being hit in asp.net MVC

I have a custom exception filter that I'm using to catch a custom exception that I wrote but for some reason when I throw my exception, it's not ever getting to the filter. Instead I just get an error that my exception was not handled by user code. Can anyone please provide some advice/assistance as to how I should have this set up? Relevant code is below:

// controller    
[CustomExceptionFilter]
    public class SomeController : Controller
    {    
        public SomeController()
        {

        }
        public ActionResult Index()
        {
            SomeClass.SomeStaticMethod();
            return View();
        }
    }

that's the controller with the customexception attribute

// some class (where exception is being thrown)
public class SomeClass
{
    public static void SomeStaticMethod()
    {
        throw new MyCustomException("Test");
    }
}

that's the class (for my test) that throws the exception (I've also tried throwing it directly on the controller).

// Custom exception filter (want this to catch all unhandled exceptions)
public class CustomExceptionFilter : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.Exception.GetType() == typeof(MyCustomException))
        {
            // do stuff
        }
    }
}

that's the custom exception filter...it's never being reached when the code is executed and the exception is thrown. Instead I get the error mentioned above. Everything I've read indicates that this is the proper way to set this up, but when I put breakpoints in my custom filter, it's never being hit....

What am I missing here?

TIA

like image 535
Kyle Avatar asked Jan 15 '10 18:01

Kyle


1 Answers

Once you've handled your error, you need to let the filter context know it has been handled. Like this:

filterContext.ExceptionHandled = true;

This should be in your '// do stuff' section.

I've copied your code, and the filter is getting called fine. The only difference I made was I added the exceptionHandled code and adding my breakpoint at that line.

like image 164
Richard Garside Avatar answered Sep 29 '22 15:09

Richard Garside