HandleErrorAttribute 派生类不捕获异常?

Rob*_*ler 5 c# custom-attributes handleerror asp.net-web-api

我有一个 ASP.NET MVC Web 应用程序,我正在尝试改进其错误处理功能。我阅读了 HandleErrorAttribute 基类,并希望将它与我的控制器类一起使用。但是,当我从使用该属性修饰的控制器类之一中的方法抛出测试异常时,不会触发派生类中的OnException覆盖。我看到的不是我的派生错误处理类的 OnException 方法被触发,而是 XML 格式的通用错误消息,并且在我的应用程序中的任何地方都找不到通用错误消息:

<Error>
    <Message>An error has occurred.</Message>
</Error>
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

请注意,我尝试将以下自定义错误元素添加到我的web.config文件中的system.web元素,如此 SO 帖子所示,但它没有帮助

ASP.net MVC [HandleError] 没有捕获异常

<customErrors mode="On" defaultRedirect="Error" />
Run Code Online (Sandbox Code Playgroud)

这是我的 HandleErrorAttribute 派生类:

public class HandleControllerErrors : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        // Breakpoint set here never hit.

        Exception ex = filterContext.Exception;
        filterContext.ExceptionHandled = true;
        var model = new HandleErrorInfo(filterContext.Exception, "Controller", "Action");

        filterContext.Result = new ViewResult()
        {
            // Use the ErrorInController view.
            ViewName = "ErrorInController",
            ViewData = new ViewDataDictionary(model)
        };
    }
} 
Run Code Online (Sandbox Code Playgroud)

这是我如何装饰我的控制器类。我有一个方法,它强行抛出一个不在try/catch块内的异常。:

[HandleControllerErrors]
public class ValuesController : ApiController
{
    [Route("Api/TestException/")]
    public IHttpActionResult TestException()
    {
        throw new InvalidCastException("Fake invalid cast exception.");
    }
}
Run Code Online (Sandbox Code Playgroud)

moa*_*ate 3

ApiController 与 MVC 控制器不同,因此这可能不起作用。Web API 中的错误处理方式略有不同。检查以下链接以获取 Web API 的异常处理属性:

http://www.asp.net/web-api/overview/error-handling/exception-handling