自定义异常过滤器未在asp.net MVC中被命中

时间:2010-01-15 18:44:42

标签: asp.net-mvc exception-handling

我有一个自定义异常过滤器,我用它来捕获我写的自定义异常,但出于某种原因,当我抛出异常时,它并没有进入过滤器。相反,我只是得到一个错误,我的异常没有被用户代码处理。任何人都可以提供一些建议/帮助,我应该如何设置这个?相关代码如下:

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

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

这是具有customexception属性的控制器

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

这是抛出异常的类(我的测试)(我也尝试将它直接扔到控制器上)。

// 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
        }
    }
}

这是自定义异常过滤器......当代码执行并抛出异常时,永远不会到达它。相反,我得到上面提到的错误。我读过的所有东西都表明这是设置它的正确方法,但是当我在我的自定义过滤器中放置断点时,它永远不会被击中....

我在这里缺少什么?

TIA

1 个答案:

答案 0 :(得分:7)

处理错误后,您需要让过滤器上下文知道它已被处理。像这样:

filterContext.ExceptionHandled = true;

这应该在你的'// do stuff'部分。

我已经复制了你的代码,过滤器被称为罚款。我做的唯一区别是我添加了exceptionHandled代码并在该行添加了断点。

相关问题