views:

149

answers:

2

Whenever an unhandled exception occurs on our site, I want to:

  • Send a notification email
  • Clear the user's session
  • Send the user to a error page ("Sorry, a problem occurred...")

The first and last I've had working for a long time but the second is causing me some issues. My Global.asax.vb includes:

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    ' Send exception report
    Dim ex As System.Exception = Nothing
    If HttpContext.Current IsNot Nothing AndAlso HttpContext.Current.Server IsNot Nothing Then
        ex = HttpContext.Current.Server.GetLastError
    End If
    Dim eh As New ErrorHandling(ex)
    eh.SendError()

    ' Clear session
    If HttpContext.Current IsNot Nothing AndAlso HttpContext.Current.Session IsNot Nothing Then
        HttpContext.Current.Session.Clear()
    End If

    ' User will now be sent to the 500 error page (by the CustomError setting in web.config)
End Sub

When I run a debug, I can see the session being cleared, but then on the next page the session is back again!

I eventually found a reference that suggests that changes to session will not be saved unless Server.ClearError is called. Unfortunately, if I add this (just below the line that sets "ex") then the CustomErrors redirect doesn't seem to kick in and I'm left with a blank page?

Is there a way around this?

A: 

Can you clear the session on your custom error page?

Also, you might want to look into using ELMAH. It makes all the stuff you are trying to do easy and awesome.

Chris
Thanks. I still have a slight issue with this approach in that it feels wrong to have the error page do cleanup but it certainly works. It also easily solves another issue I'd not considered until now where 404 errors count as Application Errors but I certainly don't want those to clear the session!
Zarigani
Yeah, it's a little wacky. My error page even logs my error to the DB, which seems pretty silly, but it works, and I have more important things to do than be academically perfect all the time. :)
Chris
A: 

I seem to have the exact opposite problem.. I'm using StateServer and after logging the error in application_error, i redirect to an error page.. but my session disappears.. and i'm not clearing it manually.. :(

Brunis