【问题标题】:How to detect in Page_Unload, that an unhandled exception has occured already?如何在 Page_Unload 中检测是否已发生未处理的异常?
【发布时间】:2013-05-01 04:54:55
【问题描述】:

即使发生未处理的异常,也会调用 Page_Unload。我需要处理这种情况。

当变量在 Page_Unload 中的状态不正确时,我有一个变量状态验证抛出异常。该异常稍后由Application_ErrorGlobal.asax 中处理。当另一个异常已经发生时,我需要抑制抛出异常。

页面:

public partial class _Default : System.Web.UI.Page
{
    private int tst = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        tst = tst / tst; //causes "Attempted to divide by zero."
        tst = 1;
    }
    protected void Page_Unload(object sender, EventArgs e)
    {
        if (tst == 0) throw new Exception("Exception on unload"); 
    }
}

全球.asax:

void Application_Error(object sender, EventArgs e)
{
    // Get the error details
    Exception lastErrorWrapper = Server.GetLastError();
    System.Diagnostics.Debug.Print(lastErrorWrapper.Message);
}

我需要在Global.asax 中得到 “试图除以零。” 但我得到 “卸载时出现异常”

给出的示例已大大简化。真实情况包括一个用户控件和一个条件编译。

我不能解决Page_Load 中的情况(例如通过捕获异常)。

【问题讨论】:

标签: c# asp.net error-handling global-asax


【解决方案1】:

你为什么不使用这样的 global.asax 方法

void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs
            // Get the error details
            Exception lastErrorWrapper = Server.GetLastError();            
            System.Diagnostics.Debug.Print(lastErrorWrapper.Message);
            Response.Redirect("~/error.aspx?q=" + lastErrorWrapper.Message);
        }

那么这里就不显示错误了,替换为:

在 web.config 中设置自定义错误页面

<customErrors mode="On" defaultRedirect="mypage.aspx">   
    </customErrors>

问候

【讨论】:

  • 我在实际应用中是这样使用的。提供的代码只是一个简化的示例。但这并不能解决问题——得到的消息与抛出的消息不同。
  • 那么需要一个更好的例子,最好有一个控制和实际数据/异常@IvanH
  • 问题要么是抑制在 Page_Unload 中的抛出,要么是在 Application_Error 中以某种方式获得“先前的异常”。发生的异常是未知的。如果我知道异常,我会阻止它而不是显示它。
  • 好吧,也许这对你有帮助thescarms.com/dotnet/unhandled.aspx
  • 另外你是否需要 page_unload 方法因为如果是这样,那么你不会得到“异常原因”,该方法将始终运行并重置你从加载方法获得的任何异常,如果你不使用它你可以在 lastErrorWrapper.InnerException 中看到异常。希望对你有帮助@IvanH
猜你喜欢
  • 2014-08-03
  • 2016-04-12
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多