c# - 如何在Page_Unload中检测到未处理的异常已经发生?

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

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

当变量在Page_Unload中的状态不正确时,我有一个变量状态验证引发异常。稍后由Application_Error中的Global.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"); 
    }
}

Global.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中的问题(例如,通过捕获异常)。

最佳答案

你为什么不这样使用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>

问候

关于c# - 如何在Page_Unload中检测到未处理的异常已经发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16415625/

相关文章:

c# - 如何管理内存有限的网格中显示的数百万行

c# - IO.Stream 到 WPF 中的图像

c# - 将 WPF 数据网格绑定(bind)到 List<List<object>>

c# - 如何使用比较验证器来比较两个下拉列表值之间的数据?

c# - 具有 utf-8 文件名的 Zip 文件

c - ANSI C : Error checking user input with a function

php - 在屏幕上打印响应标题的消息

c# - 当内容之间没有空格时 GridView 中的对齐问题

c# - 在 gridview 中,updatepanel 不工作

r - R 中的 pwr.chisq.test 错误