views:

546

answers:

2

In Global.asax, is there a way to handle SQL Timeouts elegantly, and display a message on the requesting page explaining the error? I know Global.asax has the Application_Error and Error events, but I'm not sure which (if any) I could use to accomplish this.

Related, can I access the page instance which raised the error that Global.asax is handling?

Thanks!

A: 

You could use the web.config custom errors as explained here

Locksfree
I hadn't thought of that, although, doesn't the custom errors collection only pertain to HTTP-related errors (seeing as there is a StatusCode attribute to each Error element)?
Pwninstein
I think the defaultRedirect attribute handles all errors but I may be wrong. This question seem to answer your initial query: http://stackoverflow.com/questions/1227632/asp-net-2-0-best-practice-for-writing-error-page
Locksfree
+1  A: 

In 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

In 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");
            
        }
    }
}
Jim
I ended up doing something similar to what you just posted, except instead of Response.Redirect, I used Server.Transfer("CustomErrorPage.aspx", true). We have far too many pages to redirect back to the erroring page, so instead we have a single error page that displays a message. Thanks!
Pwninstein
Glad I could help. We use the response.redirect to an error page, because we seemed to have some issues with server.transfer in certain circumstances.
Jim