HandleErrorAttribute派生类是不是捕获异常?

时间:2015-07-16 17:32:11

标签: c# asp.net-web-api custom-attributes handleerror

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

<Error>
    <Message>An error has occurred.</Message>
</Error>

我做错了什么?

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

ASP.net MVC [HandleError] not catching exceptions

<customErrors mode="On" defaultRedirect="Error" />

这是我的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)
        };
    }
} 

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

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

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

尝试将此添加到全局过滤器:

 filters.Add(new HandleControllerErrors {View = "Error"});