【问题标题】:How to handle only a specific type of Exception using the HandleError and let the rest of the Exceptions be thrown normally?如何使用 HandleError 只处理特定类型的异常,并让其余的异常正常抛出?
【发布时间】:2012-05-02 22:31:54
【问题描述】:

我正在做一个团队项目,我处于以下情况:

我创建了自己的 Exception 类,我希望处理所有抛出的 myException 类型的异常,并自动重定向到错误视图,在那里我可以很好地显示错误,这是可以的。这是我在 Web.config 中添加的内容:

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

问题是我希望所有其余的异常都能正常抛出,查看有关它的所有信息,包括堆栈跟踪、源文件和行错误,这对团队项目来说非常好。

我试过[HandleError(ExceptionType=typeof(myException)],但是没有用。

我还尝试覆盖控制器的 OnException 函数,如果异常不是 myException,那么我会再次抛出它,但我仍然会进入错误视图。

protected override void OnException(System.Web.Mvc.ExceptionContext filterContext)
{
    if (filterContext.Exception.GetType() != typeof(myException)) {
        throw filterContext.Exception;
    }
    base.OnException(filterContext);
}

有什么可行的办法吗?

谢谢。

【问题讨论】:

    标签: asp.net-mvc-3 error-handling


    【解决方案1】:

    您可以通过关闭自定义错误来获得所需的结果(这样对于所有错误,您都会显示堆栈跟踪),并将您想要的异常重定向到您需要的控制器/视图(这样看起来友好页面将显示)。

    您可以为所有控制器定义一个基本控制器,并使用以下内容覆盖其 OnException 方法:

            if (filterContext.Exception.GetType() == typeof(YourCustomException))
            {
                filterContext.ExceptionHandled = true;
                filterContext.Result = RedirectToAction("ActionName", "ControllerName", new { customMessage  = "You may want to pass a custom error message, or any other parameters here"});
            }
            else
            {
                base.OnException(filterContext);
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-24
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多