Reputation:
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!
Upvotes: 4
Views: 7997
Reputation: 43168
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.
Upvotes: 4
Reputation: 1336
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.
Upvotes: 0