views:

2414

answers:

2

I have my error handling setup to track all exceptions and write the information we need to a database and email out the developers who need to know about the error in order to fix it. The problem I run into is when the error occurs before the page has fully loaded. In this case the session variables I want to track are not available in Application_Error. So I do the following so that I don't get an error in my error handling, but there has to be a better way. Also if the page loads and the error occurs on submission of the form then the session variables are available.

try
{
    user_name = System.Web.HttpContext.Current.Session["User_Name"].ToString();
    user_number = System.Convert.ToInt32(System.Web.HttpContext.Current.Session["User_Number"].ToString());
}
catch (Exception ex)
{
    user_number = 0; 
    user_name = "N/A";     
}

Any help is greatly appreciated. Thanks!

A: 

This is what you'll need to do. The user can go to any page through a bookmark or by knowing the URL. Therefore, the page could possibly be retrieved by the user before any values are set. So that is what you'll need to do to make sure the code doesn't break.

Tommy Hui
+1  A: 

There's nothing wrong with what you're doing, although an

if ( null != System.Web.HttpContext.Current.Session )

would be more "surgical" than your try-catch block.

Session is not initialized until the AcquireRequestState event, so any error occurring before this point will not have session variables available.

harpo
Hi Harpo, Thanks for your response!Currently our error logging catches the errors page by page and spits them back to the user(stupid I know) but if we have trace on then you see the session information in the trace. There has to be a way of getting that information on the application_error event?
Again, an error can fire at any time, including points in the page lifecycle before the session becomes available to the page. There is no rule that session cannot be null. So it is reasonable, indeed prudent to perform this check.
harpo