【问题标题】:C# ASP.NET Page_Error doesn't handle exceptionC# ASP.NET Page_Error 不处理异常
【发布时间】:2019-08-31 02:11:22
【问题描述】:

event Page_Error(object sender, EventArgs e) 不处理期望。 Visual Studio 正在处理异常。

我尝试通过 Page_Load 或按钮抛出异常,但仍然无法正常工作。我无法搜索有关此问题的任何信息。在我的书中展示了带有 Page_Load、Page_Error、Button 的简单示例,根据我的书,这应该可以工作。我猜在 Web.config 中缺少一些东西。

    void Page_Error(object sender, EventArgs e)
    {
        Response.Clear();
        Exception ex = Server.GetLastError();
        Response.Write("Something not yet");
        Response.Write(ex.Message);
        Server.ClearError();
    }

protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("Load event fired");
        throw new Exception();
    }

我希望 Page_Error 会处理抛出的异常,而不是 Visual Studio。

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    您可以在 global.asax 中处理应用程序(Application_Error)级别的错误并将请求转发到自定义错误页面。

    这个 SO 线程可能很好看: Exception handling in ASP.NET Webforms

    【讨论】:

    • 这绝对是更适合在 ASP.NET 中捕获异常的方法,但在这种情况下,我想知道事件 Page_Error 不处理异常的原因是什么,尽管所有书籍或教程都说它应该。
    【解决方案2】:

    尝试将您的 Page_Error 方法设为受保护:

    protected void Page_Error(object sender, EventArgs e)
        {
            Response.Clear();
            Exception ex = Server.GetLastError();
            Response.Write("Something not yet");
            Response.Write(ex.Message);
            Server.ClearError();
        }
    

    【讨论】:

    • 还是不行。 VS 正在处理异常,而不是方法。感谢您的尝试
    • Visual Studio 正在处理异常是什么意思?您是否尝试在 Page_Error 处理程序中放置断点?
    • 好吧,我注意到它是如何工作的。 VS 正在抛出异常声明,但如果我执行下一行,我将跳转到事件 Page_Error。据我了解,VS 不应该抛出异常声明。事件 Page_Error 应该作为 try/catch 工作。现在正在运行该异常正在抛出程序,并且下一个程序跳转到 page_error。
    【解决方案3】:

    您抛出了错误类型的异常。抛出 ApplicationException 而不是 Exception

    【讨论】:

      猜你喜欢
      • 2017-03-25
      • 2014-12-19
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      • 2012-06-11
      • 2011-04-27
      • 2011-09-11
      • 1970-01-01
      相关资源
      最近更新 更多