开发者

Custom Exception Filter not being hit in asp.net MVC

开发者 https://www.devze.com 2022-12-16 18:43 出处:网络
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 erro

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(Ex开发者_JAVA百科ceptionContext 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号