Custom Exception Filter not being hit in asp.net MVC

怎甘沉沦 提交于 2019-12-22 03:17:29

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/2073925/custom-exception-filter-not-being-hit-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!