Application_Error不会触发?

Chr*_*ers 6 .net asp.net onerror global-asax

在Webform1.aspx.cs中:

protected void Page_Load(object sender, EventArgs e)
{
    throw new Exception("test exception");
}
Run Code Online (Sandbox Code Playgroud)

在Global.asax.cs中:

protected void Application_Error(object sender, EventArgs e)
{
    // Code that runs when an unhandled error occurs
    if (Server.GetLastError() is HttpUnhandledException)
        Server.Transfer("ErrUnknown.aspx");
}
Run Code Online (Sandbox Code Playgroud)

但是从不调用Application_Error事件处理程序.相反,我得到一个运行时错误页面.

在抛出异常后,我需要做什么才能调用Application_Error?

Waq*_*aja 5

它看起来很好,应该调用Application_Error.

你有没有通过Debugging你的申请检查?

实际上你错过了Server.ClearError()所以异常被传递给asp.net但你应该在这里压制它,因为你自己处理它.

protected void Application_Error(object sender, EventArgs e)
{
    // Code that runs when an unhandled error occurs
    if (Server.GetLastError() is HttpUnhandledException)
    {
        // suppressing the error so it should not pass to asp.net
        Server.ClearError();
        Server.Transfer("ErrUnknown.aspx");
    }
}
Run Code Online (Sandbox Code Playgroud)