【问题标题】:Can I show an alert from Global.asax on a page that's experiencing a SQL Timeout?我可以在遇到 SQL 超时的页面上显示来自 Global.asax 的警报吗?
【发布时间】:2009-09-17 16:51:01
【问题描述】:

在 Global.asax 中,有没有一种方法可以优雅地处理 SQL 超时,并在请求页面上显示一条消息来解释错误?我知道 Global.asax 有 Application_Error 和 Error 事件,但我不确定我可以使用哪个(如果有的话)来完成这个。

相关,我可以访问引发 Global.asax 正在处理的错误的页面实例吗?

谢谢!

【问题讨论】:

    标签: vb.net exception-handling asp.net-2.0 global-asax


    【解决方案1】:

    在 global.asax.vb 中

    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    
            If TypeOf (Context.Error.GetBaseException) Is System.Data.SqlClient.SqlException Then
    
                Dim ex As System.Data.SqlClient.SqlException = Context.Error.GetBaseException
    
                If (ex.Errors.Count = 1 And ex.Number = -2) Then
    
                    Server.ClearError()
    
                    Response.Redirect(Context.Request.Url.ToString() & "?error=MessageHere")
    
                End If
    
    
            End If
    
    End Sub
    

    在 C# 中

    public void Application_Error(object sender, EventArgs e)
    {
        if ((Context.Error.GetBaseException) is System.Data.SqlClient.SqlException) {
            
            System.Data.SqlClient.SqlException ex = Context.Error.GetBaseException;
            
            if ((ex.Errors.Count == 1 & ex.Number == -2)) {
                
                Server.ClearError();
                    
                Response.Redirect(Context.Request.Url.ToString() + "?error=MessageHere");
                
            }
        }
    }
    

    【讨论】:

    • 我最终做了与您刚刚发布的内容类似的事情,除了 Response.Redirect,我使用了 Server.Transfer("CustomErrorPage.aspx", true)。我们有太多页面需要重定向回错误页面,因此我们只有一个显示消息的错误页面。谢谢!
    • 很高兴我能帮上忙。我们使用 response.redirect 到一个错误页面,因为在某些情况下我们似乎对 server.transfer 有一些问题。
    【解决方案2】:

    您可以使用 web.config 自定义错误as explained here

    【讨论】:

    • 我没有想到,虽然自定义错误集合不只与 HTTP 相关的错误有关(因为每个 Error 元素都有一个 StatusCode 属性)?
    • 我认为 defaultRedirect 属性可以处理所有错误,但我可能错了。这个问题似乎回答了您最初的疑问:stackoverflow.com/questions/1227632/…
    猜你喜欢
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多