gpt4 book ai didi

asp.net-mvc - ExceptionContext.ExceptionHandled 更改为 true。异常在哪里处理?

转载 作者:行者123 更新时间:2023-12-01 19:11:47 25 4
gpt4 key购买 nike

我正在使用全局操作过滤器来处理和记录所有异常。

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ElmahHandleErrorAttribute());
filters.Add(new HandleErrorAttribute());
}

这就是全局操作过滤器 ElmahHandleErrorAttribute 的定义方式 - 它重写 OnException 方法。

public class ElmahHandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
public override void OnException(ExceptionContext context)
{
//Is the exception handled already? context.ExceptionHandled seems to be true here
if (!context.IsChildAction && (context.HttpContext.IsCustomErrorEnabled))
{
//Do other stuff stuff
//Log to Elmah
}
}
...
}

我不明白为什么当OnException方法执行时context.ExceptionHandled的值为true。如何处理这个异常?

-编辑-我在 Web.Config 中有一个 customErrors 部分。我有一个 ErrorController 类,以及名为 GeneralHttp404 的操作。

<customErrors mode ="On" defaultRedirect="Error/General">
<error statusCode="404" redirect="Error/Http404"/>
</customErrors>

我不明白的是, Controller 操作 General 未执行(永远不会命中断点),但 ExceptionContext.ExceptionHandled 的值是当 ElmahHandleErrorAttributeOnException 方法开始执行时设置为 true。

最佳答案

发生异常时,全局过滤器的执行顺序为in reverse order 。这意味着 HandleErrorAttribute 首先运行。

可以查看HandleErrorAttribute的代码here ,但简而言之,它:

  1. 仅在 ExceptionHandled 为 false 且启用自定义错误时执行。
  2. 设置到错误 View 的重定向,默认情况下称为Error
  3. ExceptionHandled 设置为 true。

由于它是第一个过滤器,因此执行时 ExceptionHandled 为 false,导致它将 View 设置为 Error 并将 ExceptionHandled 设置为 true。因此,当您自己的过滤器执行时,这就是为什么 ExceptionHandled 已经设置为 true 的原因。请注意,如果禁用自定义错误,则 ExceptionHandled 仍将为 false,因为 HandleErrorAttribute 不会完成其工作。在这种情况下,ELMAH 无论如何都会记录错误,因为它未处理(黄色死屏),因此类中的测试是为了防止重复记录错误。

现在,关于为什么不执行 General 操作的另一个问题,仅当过滤器本身未设置某些显式重定向时才使用 defaultRedirect ,因此当 ActionMethod 内部发生异常并且您注册了全局过滤器 HandleErrorAttribute 时,它实际上会被忽略。但是,如果您输入的 URL 不存在(即 ActionMethod 中未发生错误),则会调用该函数。另外,如果您在 Global.asax.cs 中注释掉用于注册 HandleErrorAttribute 的行,那么您将始终执行 General Controller 操作。

关于asp.net-mvc - ExceptionContext.ExceptionHandled 更改为 true。异常在哪里处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10597478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com