Accessing SessionState in Application_Error

N

Nemisis

Hi everyone,

I am trying to create a custom error page, that the user gets shown
when a error has occurred within my website. The code works
perfectly, apart from when an invalid URL is typed in, then i am
unable to pass the exception from the global.asax file to the page via
the sessionstate. Everytime i try to pass something into the
sessionstate i get a error message of 'Object reference not set to an
instance of an object.'

Does anyone know how to get around this error? My code is below

GLOBAL.ASAX PAGE CODE

Sub Application_Error(ByVal sender As Object, ByVal e As
EventArgs)
' Fires when an error occurs

Dim ctx As HttpContext = HttpContext.Current
Dim LastException As Exception = ctx.Server.GetLastError
Dim Exception As New ExceptionItem(LastException)

' clear the error
ctx.Server.ClearError()

HttpContext.Current.Session("HELLO") = "AAA"
HttpContext.Current.Session.Add("LastException", Exception)

Me.Response.Redirect("~/Errors/GeneralError.aspx")
End Sub


CUSTOM ERROR PAGE CODE

Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load

Dim Master As eContrack = Page.Master

Master.SectionTitle = "An error has occurred"

' Session("LastException") is created in the Error event
of global.asax
Dim Exception As ExceptionItem =
CType(Session("LastException"), ExceptionItem)

Exception.Insert()

' See if errors should be sent by email
If
ConfigurationManager.AppSettings("SendErrorByEmail").ToString = "true"
Then


Exception.Email(ConfigurationManager.AppSettings("SendErrorToEmail"),
HelperMethod.GetDns)

End If

End Sub

Thanks in advance
 
M

Mike Hofer

Hi everyone,

I am trying to create a custom error page, that the user gets shown
when a error has occurred within my website. The code works
perfectly, apart from when an invalid URL is typed in, then i am
unable to pass the exception from the global.asax file to the page via
the sessionstate. Everytime i try to pass something into the
sessionstate i get a error message of 'Object reference not set to an
instance of an object.'

Does anyone know how to get around this error? My code is below

GLOBAL.ASAX PAGE CODE

Sub Application_Error(ByVal sender As Object, ByVal e As
EventArgs)
' Fires when an error occurs

Dim ctx As HttpContext = HttpContext.Current
Dim LastException As Exception = ctx.Server.GetLastError
Dim Exception As New ExceptionItem(LastException)

' clear the error
ctx.Server.ClearError()

HttpContext.Current.Session("HELLO") = "AAA"
HttpContext.Current.Session.Add("LastException", Exception)

Me.Response.Redirect("~/Errors/GeneralError.aspx")
End Sub

CUSTOM ERROR PAGE CODE

Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load

Dim Master As eContrack = Page.Master

Master.SectionTitle = "An error has occurred"

' Session("LastException") is created in the Error event
of global.asax
Dim Exception As ExceptionItem =
CType(Session("LastException"), ExceptionItem)

Exception.Insert()

' See if errors should be sent by email
If
ConfigurationManager.AppSettings("SendErrorByEmail").ToString = "true"
Then

Exception.Email(ConfigurationManager.AppSettings("SendErrorToEmail"),
HelperMethod.GetDns)

End If

End Sub

Thanks in advance

Please forgive me for being thickheaded; I get like that sometimes.
You're describing a NullReferenceException. I'm not certain if it's
happening in global.asax or if it's happening in your custom error
page. I *think* it's happening in the custom error page.

If it's happening in the custom error page, its meaning will depend on
the line that the exception is occurring on. If it's happening on the
line where you're retreiving data from the session, I'd surmise that
it means that you either (a) don't have a session or (b) have a new
session and the value you're asking for isn't there.

However, I don't know what line the exception is being thrown from.
Could you be a little more specific?

Thanks!
 
N

Nemisis

Please forgive me for being thickheaded; I get like that sometimes.
You're describing a NullReferenceException. I'm not certain if it's
happening in global.asax or if it's happening in your custom error
page. I *think* it's happening in the custom error page.

If it's happening in the custom error page, its meaning will depend on
the line that the exception is occurring on. If it's happening on the
line where you're retreiving data from the session, I'd surmise that
it means that you either (a) don't have a session or (b) have a new
session and the value you're asking for isn't there.

However, I don't know what line the exception is being thrown from.
Could you be a little more specific?

Sorry, i forgot to say where the error is occurring, Duh. lol.

The error is occurring when i try and set a session variable in the
global.asax file. The exact line where the error occurs is.

HttpContext.Current.Session.Add("LastException", Exception)

I have even tried writing it like

HttpContext.Current.Session("LastException") = Exception


but that still doesnt work. I have checked that Exception actually
does have values set, and it does. And to even test it further, i
wrote in the following line of code to test setting a session
variable, and it still comes up with the same error.

HttpContext.Current.Session("HELLO") = "AAA"

I would really appreicate any help and insight as to why this is
happening. Thanks again
 
N

Nemisis

Sorry i forgot to write what line is causing the error Duh! :)

It is on the global.asax file when i am trying to set the value of a
session variable. The line is :

HttpContext.Current.Session.Add("LastException", Exception)

I have even tried to change it so it reads

HttpContext.Current.Session("LastException") = Exception

but that still doesnt work. I do no that there is a value in
Exception, so i am not trying to store a null object. I even tried
the following line, and i am still getting the error.

HttpContext.Current.Session("HELLO") = "AAA"

I would really appreciate any insight to this problem. Cheers
 
N

Nemisis

Sorry i forgot to write what line is causing the error Duh! :)

It is on the global.asax file when i am trying to set the value of a
session variable. The line is :

HttpContext.Current.Session.Add("LastException", Exception)

I have even tried to change it so it reads

HttpContext.Current.Session("LastException") = Exception

but that still doesnt work. I do no that there is a value in
Exception, so i am not trying to store a null object. I even tried
the following line, and i am still getting the error.

HttpContext.Current.Session("HELLO") = "AAA"

I would really appreciate any insight to this problem. Cheers
 
J

John Saunders

Nemisis said:
Sorry, i forgot to say where the error is occurring, Duh. lol.

The error is occurring when i try and set a session variable in the
global.asax file. The exact line where the error occurs is.

HttpContext.Current.Session.Add("LastException", Exception)

I bet that HttpContext.Current.Session is Nothing, or else
HttpContext.Current is Nothing. Check to see which.

John
 
M

Mike Hofer

Sorry, i forgot to say where the error is occurring, Duh. lol.

The error is occurring when i try and set a session variable in the
global.asax file. The exact line where the error occurs is.

HttpContext.Current.Session.Add("LastException", Exception)

I have even tried writing it like

HttpContext.Current.Session("LastException") = Exception

but that still doesnt work. I have checked that Exception actually
does have values set, and it does. And to even test it further, i
wrote in the following line of code to test setting a session
variable, and it still comes up with the same error.

HttpContext.Current.Session("HELLO") = "AAA"

I would really appreicate any help and insight as to why this is
happening. Thanks again

If the error is occurring there, then the problem is that you don't
have a valid session object. This is born out by the fact that you've
tried twice to write two different variables to the session, and both
of them raise the same exception.

So the next question I have for you is this: What is the exception
that is putting you in this exception handler in the first place?
Whatever it is, it's apparently occurring before you have a valid
session, or it's disconnecting the user from their session. I'd look
there.

Without a valid session, you won't be able to cache the exception
information in it. To prevent the NullReferenceException, wrap the
offending statement in a conditional, as follows (assuming VB.NET):

If Not HttpContext.Current.Session Is Nothing Then
HttpContext.Current.Session.Add("LastException", Exception)
End If

Hope this helps!

Mike
 
N

Nemisis

If the error is occurring there, then the problem is that you don't
have a valid session object. This is born out by the fact that you've
tried twice to write two different variables to the session, and both
of them raise the same exception.

So the next question I have for you is this: What is the exception
that is putting you in this exception handler in the first place?
Whatever it is, it's apparently occurring before you have a valid
session, or it's disconnecting the user from their session. I'd look
there.

Without a valid session, you won't be able to cache the exception
information in it. To prevent the NullReferenceException, wrap the
offending statement in a conditional, as follows (assuming VB.NET):

If Not HttpContext.Current.Session Is Nothing Then
HttpContext.Current.Session.Add("LastException", Exception)
End If

Hope this helps!

Mike

In order to get this error, i am trying to navigate to a page that
doesnt exist on my site ie. Home4.aspx. This causes the
application_Error sub to be called, but the session is empty/null. If
i create a standard page, and write Throw New Exception(), again, the
application_error code is called, but the session IS VALID, and i do
not get a NullReferenceException.

Why do you get a nullreferenceexception on a 404 error? Is it because
the page is not apart of your application, thus the session wont exist?
 
M

Mike Hofer

In order to get this error, i am trying to navigate to a page that
doesnt exist on my site ie. Home4.aspx. This causes the
application_Error sub to be called, but the session is empty/null. If
i create a standard page, and write Throw New Exception(), again, the
application_error code is called, but the session IS VALID, and i do
not get a NullReferenceException.

Why do you get a nullreferenceexception on a 404 error? Is it because
the page is not apart of your application, thus the session wont exist?- Hide quoted text -

- Show quoted text -

Without seeing your code, I couldn't specifically answer your
question. :(

A 404 is generated for a number of reasons, however, and not always
because a page couldn't be found. (Microsoft might like you to believe
that a 404 is *always* raised for that reason, but you shouldn't just
take their word for it.)

First off, you know that the exception is occurring. I'd start by
addressing the exception. It sounds like you're trying to treat the
symptom (the fact that you don't have a session variable in your error
handler) instead of dealing with its cause (the fact that you're on
the error page to begin with).

Why are you even *on* this error page? How did you get here? What is
the condition that got you here? That's the defect that needs to be
resolved. Wrap that code in an exception handler. Don't rely on
global.asax to handle your exceptions. It's a FAILSAFE, not your main
exception handler.

Check this article out: http://aspnetresources.com/articles/CustomErrorPages.aspx

I'm not sure how familiar you are with this stuff, but it might shed
some light on the best practices for exception handling in ASP.NET.

Again, I hope I'm helping and not just confusing the snot out of ya.

Mike
 
N

Nemisis

Mike,

1. My code is at the top of the forum, u must of missed it.
2. I think i have not explained myself correctly, or you are not
getting what i mean. I can handle exceptions, that it fine, but i
just want to know why i cant get access to session variables when i am
in the application_error sub, when i cause an error by directing to an
invalid/non existant page?
3. That is one of the articles i have read, it is a good article, and
as you can see my code is very similar
 
M

Mike Hofer

Mike,

1. My code is at the top of the forum, u must of missed it.
2. I think i have not explained myself correctly, or you are not
getting what i mean. I can handle exceptions, that it fine, but i
just want to know why i cant get access to session variables when i am
in the application_error sub, when i cause an error by directing to an
invalid/non existant page?
3. That is one of the articles i have read, it is a good article, and
as you can see my code is very similar

Hi Nemesis,

The miscommunication is on my part. The code I was talking about
seeing was the part that triggers the redirection to the external
page. I failed to make that clear. I do that a lot. It's a nasty
habit, and one I'll try to correct. Is that code wrapped in its own
Try...Catch block?

I've been reviewing the code from your original post, and I've been
wondering about the actual exception that was thrown that landed you
in the exception handler. I know that from my own personal experience,
any number of odd exceptions can be thrown, and they'll generate the
404 page.

For example, I saw this occur because I had a validator set up on a
WebForm with no control to validate. The system kept reporting 404 for
a page I *knew* was there. I couldn't figure it out until I set a
break point in the global exception handler and examined the actual
exception that had landed me there. That's when I saw the actual
exception, and was able to examine the stack trace to figure out where
it was occurring.

My point is that you may not be experiencing a true 404. It's just a
theory, but it's worth disproving it. I'd suggest setting a breakpoint
on this line in your Application_Error event handler in Global.asax:

ctx.Server.ClearError()

When you hit it, pull up the Locals window and examine the exception.
It might reveal something about a runtime defect that you're not aware
of, and that prevents the page from being rendered properly on either
initial rendering or postback.

Again, it's just a theory, but it's worth disproving. If you've
already tried that, that's great. I know that when inexplicable errors
occur in my application, it's the first thing I do now. The results
are usually quite telling.

As far as why you're not getting a session object after a 404 occurs,
that's a stumper. Session state isn't available until *after* the
Application_OnAuthenticateRequest event has fired. If the error is
occuring before that event has fired, that may be why you're not
seeing any session state. (For details, see:
http://msdn.microsoft.com/library/d...us/cpguide/html/cpconhandlingpublicevents.asp)

Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top