asp. net error handling Application_Error event example

  • 2020-10-07 18:37:36
  • OfStack

ASP. NET error handling Example Application_Error events:

New web program - New ES8en.aspx page - add the following code to the page:


<SCRIPT language=C# runat="server">
void Page_Load(object sender, System.EventArgs e)
{
throw(new ArgumentNullException());
}
</SCRIPT>

Next, add the Application_Error event to the Global.asax file to catch the error raised in the Page_Load event on the AppEvent.aspx page. Add the following code to the Global.asax file:


protected void Application_Error(object sender, EventArgs e)
{
Exception objErr = Server.GetLastError().GetBaseException(); // Get error  keleyi.com
string err ="Error Caught in Application_Error event/n" +
"Error in:" + Request.Url.ToString() +
"/nError Message:"+ objErr.Message.ToString() +
"/nStack Trace:"+ objErr.StackTrace.ToString();
// Writes the captured error windows Application logs are accessible from the event viewer. 
System.Diagnostics.EventLog.WriteEntry("Test2", err, System.Diagnostics.EventLogEntryType.Error);
Server.ClearError(); // The exception is cleared and no longer caught elsewhere. 
}

Save what you just did, in Visual ES31en.NET, on the Build menu, click Build. Right-click the page, and then click view in your browser. In this case the page will be blank, but you should notice that a new entry has been added to the event log. This example generates an entry in the application log that can be accessed from the event viewer. After logging an error, you may want to redirect the user to another user-friendly error page or perform 1 additional action as needed, which you can do as you wish.


Related articles: