Application_Error() not firing

本文关键字:not firing Error Application | 更新日期: 2023-09-27 17:56:10

我正在尝试运行一个将异常记录到数据库的 ASP.NET 应用程序。我正在使用Application_Error来捕获异常。

在添加连接字符串之前,只是为了测试我的代码(记录器类和 Global.asax 中的代码),我尝试将错误记录到 Windows 事件查看器中。这按预期工作。

但是,在将连接字符串添加到 Web.config 文件并添加 ADO.NET 代码后,我尝试运行该应用程序。但是我得到了黄色的死机:D

我不知道我的代码出了什么问题。我只修改了 Web.config 文件中的 connectionString 元素并添加了 ADO.NET 代码。

这是代码。

这是 Page_Load 事件中的 Web 表单代码。国家/地区.xml文件不存在,预计会引发错误。

DataSet dataset = new DataSet();
dataset.ReadXml(Server.MapPath("~/Countries.xml"));
GridView1.DataSource = dataset;
GridView1.DataBind();

Application_Error

Exception exception = Server.GetLastError();
if (exception != null)
{
Logger.Log(exception);
Server.ClearError();
Server.Transfer("~/Errors.aspx");
}

网络.config

<configuration>
<connectionStrings>
    <add name="DBCS" connectionString="Data Source=.;database=Sample;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
  </connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
</system.web>
</configuration>

我尝试通过在 Global.asax 中的 Application_Error 方法放置断点来进行调试,但控件从未达到该点。异常是从Page_Load事件触发的。记录器类代码中没有编译错误。另外,我不想使用自定义错误路由来解决此问题。

提前谢谢。

这是代码的链接:https://drive.google.com/folderview?id=0B5K22Q9r50wXU0VOQmJKVHBoaDg&usp=sharing

Application_Error() not firing

如果在调试时遇到<customErrors mode="Off" />,代码将无法到达Application_Error事件,因为异常会立即显示在浏览器中。

如果要在调试时达到Application_Error,则需要启用自定义错误 -

<customErrors mode="On" defaultRedirect="~/Error.aspx" />

您是否在 web.config 上启用了自定义错误?

<system.web>
    ...
    <customErrors mode="RemoteOnly" defaultRedirect="~/Errors.aspx" redirectMode="ResponseRewrite" />
    ...
</system.web>

请注意,重定向模式为"响应重写",以保留Server.GetLastError()异常。如果以其他方式设置,则Server.GetLastError()将返回 null。

在Global.asax中实现Application_Error应该很容易。

protected void Application_Error(Object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    if (ex is ThreadAbortException)
        return; // Redirects may cause this exception..
    Logger.Error(LoggerType.Global, ex, "Exception");
    Response.Redirect("unexpectederror.htm");
}

更新:

可能的罪魁祸首是在 Global.asax 上注册为过滤器的 HandlerErrorAttribute。

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute()); // this line is the culprit
}

只需注释掉或删除该行,并确保已在 web.config 下的 system.web 中实现了 customErrors。

我对 HandleErrorAttribute 不太熟悉,如果这解决了您的问题,那么不妨查找其文档。

就我而言,我在此事件处理程序中存在错误日志记录 (sentry.io),并且日志记录算法本身会导致错误,从而重定向到 web.config 中定义的错误页面,我也认为它没有触发。确保在错误处理程序中也对代码使用 try-catch,以便调试案例。即。将异常详细信息刷新为响应并结束响应。

这是我要 sentry.io 的错误记录器:

public static void LogException(Exception ex, bool redirect = true)
{
    if (ex != null)
    {
        if (HttpContext.Current.Request.IsLocal)
        {
            throw ex;
        }
        // ignore Response.Redirect errors
        if (ex.GetType() == typeof(ThreadAbortException))
        {
            return;
        }
        var sentryApiKey = GetAppSetting("SentryIO.ApiKey");
        if (string.IsNullOrEmpty(sentryApiKey))
        {
            throw new NullReferenceException("SentryIO.ApiKey not defined as app setting.");
        }
        var ravenClient = new RavenClient(sentryApiKey);
        ravenClient.Capture(new SentryEvent(ex));
        if (redirect)
        {
            HttpContext.Current.Response.StatusCode = 404;
            HttpContext.Current.Response.Redirect("/?500-error-logged");
        }
    }
}

正如我所看到的,在发布模式下构建或具有如下所示的 web.config 不会阻止此事件触发。

<compilation debug="false" targetFramework="4.5.2" />
<customErrors mode="RemoteOnly" defaultRedirect="errordocs/500.htm">
    <error statusCode="403" redirect="errordocs/403.htm" />
    <error statusCode="404" redirect="errordocs/404.htm" />
</customErrors>
对我来说

,问题是endResponse被设置为false

我从false更改为true,它解决了问题:

HttpContext.Current.Response.Redirect($"/e/{errorId}", true);