473,387 Members | 1,504 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Accessing SessionState in Application_Error

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

Mar 12 '07 #1
10 2332
On Mar 12, 1:07 pm, "Nemisis" <darrens2...@hotmail.comwrote:
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!

Mar 12 '07 #2
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

Mar 13 '07 #3
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

Mar 13 '07 #4
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

Mar 13 '07 #5
"Nemisis" <da*********@hotmail.comwrote in message
news:11**********************@30g2000cwc.googlegro ups.com...
>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 bet that HttpContext.Current.Session is Nothing, or else
HttpContext.Current is Nothing. Check to see which.

John
Mar 13 '07 #6
On Mar 13, 5:13 am, "Nemisis" <darrens2...@hotmail.comwrote:
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
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

Mar 13 '07 #7
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?

Mar 13 '07 #8
On Mar 13, 11:10 am, "Nemisis" <darrens2...@hotmail.comwrote:
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?- 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/...rrorPages.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

Mar 13 '07 #9
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
Mar 15 '07 #10
On Mar 15, 11:23 am, "Nemisis" <darrens2...@hotmail.comwrote:
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/de...blicevents.asp)

Mike

Mar 15 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: | last post by:
Is it possible to access the previous page's viewstate directly through the context object after a server.transfer. If so, how? The way i'm doing it is saving all needed items to a structure on...
1
by: Greg Burns | last post by:
I am trying to write a global custom error page. I thought I would jot down some of what I've learned so far... At first I just used the default customErrors section with a defaultRedirect tag,...
0
by: Michael | last post by:
Hi, I have an ASP.NET application that catches un-handled exceptions in the Application_Error method and writes the details to the Event Log. But, if I do a Server.ClearError() followed by either...
0
by: Michael | last post by:
Hi, I have an ASP.NET application that catches un-handled exceptions in the Application_Error method and writes the details to the Event Log. But, if I do a Server.ClearError() followed by either...
2
by: Carl Johansen | last post by:
I've been reading the O'Reilly "ASP.NET Cookbook" 1st edition (Kittel and LeBlond), and it makes a recommendation about exception handling that seems a bit strange. They say that, if you want to...
0
by: Joergen Bech | last post by:
Fairly new to ASP.NET 1.1. Getting the error below when running application on a web server outside of my control, but only the first time I run it: 1. After a long period of inactivity (or...
6
by: Matt | last post by:
Can anyone give me a good reason to use BOTH application scope Page_Error and the page scope Page_Error when trapping errors in a web application? Is there any real benefit to using the Page_Error...
2
by: Matt | last post by:
As the subject says... are Application_Error and Page_Error triggered by the same event? In other words, is there any error that could slip by Application_Error but be caught by Page_Error, or...
3
by: Alex Maghen | last post by:
I want to create an object which is attached to the specific user session and I want to be able to access that object directly throughout the Pages, Page Controls, and Master Pages of the site. ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.