« Home | Error Handling in .net 3.5 » | Using LINQ in String Collections » | SQL in .net Using LINQ » | Querying the DataTable in .Net » | Converting DataView into DataTable » | Deleting TFS Project »

Handling Application_Error Method

Similar to the Page_Error event handler, you can use the Application_Error event handler to trap errors that occur in your application. Due to the event's application-wide scope, you can log of application error information or handle other application-level errors that may occur.

The sample to follow is based on the preceding Page_Error code sample and would be fired if the error in Page_Load was not trapped in the Page_Error event handler. The Application_Error event handler is specified in the Global.asax file of your application. For simplicity, the steps in this section create a new page in which to throw the exception, trap the error in the Application_Error event handler of the Global.asax file, and write the error to the event log. The following steps demonstrate how to use the Application_Error method:

1. Add a new file named AppEvent.aspx to your project.
2. Add the following code to AppEvent.aspx:

void Page_Load(object sender, System.EventArgs e)
{
throw(new ArgumentNullException());
}


Note The information discussed in the "Page_Error" section about the AutoEventWireup attribute also applies to the code sample in this step. See the information in the "Page_Error" section for more details.
3. From the File menu, click Save AppEvent.aspx.
4. Add the Application_Error event handler to the Global.asax file to trap the error that you throw in the Page_Load event handler of the AppEvent.aspx page. Notice that you must add another using statement for the System.Diagnostics namespace to Global.asax to use the event log.

Add the following code to the Global.asax file:
using System.Diagnostics;

protected void Application_Error(object sender, EventArgs e)
{
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error Caught in Application_Error event\n" +
"Error in: " + Request.Url.ToString() +
"\nError Message:" + objErr.Message.ToString()+
"\nStack Trace:" + objErr.StackTrace.ToString();
EventLog.WriteEntry("Sample_WebApp",err,EventLogEntryType.Error);
Server.ClearError();
//additional actions...
}


5. Save the Global.asax file.
6. In Visual Studio .NET, on the Build menu, click Build.
7. Right-click the page, and then click View in Browser. In this case the page will be blank, however, you should notice that a new entry has been added in the event log. This sample makes an entry in the Application log, which is accessible from the Event Viewer. After logging the error you might want to redirect the user to another more user-friendly error page, or perform some additional actions if needed.


Error Handling in Web.Config

Labels: , , , ,

Post a Comment