Monday, October 6, 2008

Custom Error Handling in ASP.Net

Custom Error Handling in ASP.Net

There are often Required to Handle Error (Not Try Catch Handling) 
Which Mostly Genertaed by Server and Need to give
Custom Message on Page.And you Can Save This Error in EventView 
or You can Send mail to Administrator About
this Erorr Generated on Server.


In ASP.net 2.0 This Can be Done by making Small Changes in Web.Config,
Global.Aspx and One Error Page.



First Generate One Error Page Which Give User Friendly Message like


              We are very sorry for the inconvenience 
caused to you...

Second in Global.Aspx in Application_Error Section Generate One Event Log
Or you Can Mail Error 
to Administrator.

 void Application_Error(object sender, EventArgs e) 
    {
            // Code that runs when an unhandled error occurs
            Exception ex = Server.GetLastError();
            String errordescription = Server.GetLastError().ToString();
            string eventlogname = "Software_Error";
            if (EventLog.SourceExists(eventlogname) == false)
            {
                EventLog.CreateEventSource(eventlogname, eventlogname);
            }
            EventLog Log = new EventLog();

            Log.Source = eventlogname;
            Log.Clear();
            Log.WriteEntry(errordescription, EventLogEntryType.Error);

            //Here you Can Write Mail Message Coding Also
    }



In Web.Config Change CustomError mode on And ErrorPages to Your Error Page

< customErrors defaultRedirect="error.aspx" mode="On" / >


Prev Post                                                      All Post                                                           Next Post



1 comment: