asp. net error catching of error handling page_error event use method

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

ASP.NET provides three main methods for catching and responding to errors when they occur: page_error events, application_error events, and the application configuration file (Web.config).

The main purpose of these three methods is nothing more than to create custom error reports. The purpose of creating custom error reports is nothing more than to show the user friendly error pages and improve the program's friendliness for security reasons.

The Page_Error event is illustrated as follows:

This example displays detailed error information in the browser and is provided for illustration purposes only. Showing the end user of an application the details of an error can be very dangerous (especially the web program). It is more appropriate to display a message to the user telling him that an error has occurred, and then record the specific error information in the event log.

This example intentionally throws an empty exception in the Page_Load event to test the Page_Error event.

Example: Create the web program - Create a new page PageEvent.aspx and then add the following code to PageEvent.aspx:


<script language="C#" runat="server">
void Page_Load(object sender, System.EventArgs e)
{
//  Raises an empty reference exception  keleyi.com
throw (new ArgumentNullException());
}
protected void Page_Error(object sender, EventArgs e) 
{
Exception objErr = Server.GetLastError().GetBaseException(); //  Get error 
string err = "1.error in: &nbsp; &nbsp; &nbsp;" + Request.Url.ToString() + "</br>" +
"2.error Message: &nbsp; &nbsp; &nbsp;" + objErr.Message.ToString() + "</br>" +
"3.stack Trace: &nbsp; &nbsp; &nbsp;" + objErr.StackTrace.ToString() + "</br>";
Response.Write(err.ToString()); // Output error message 
// Response.Redirect("ErrorPage.htm"); // You can redirect to a friendly error page 
Server.ClearError();
}
</script>

Save, right - click the page - view in browser to see the captured custom error message


Related articles: