Examples of three ways to catch global unhandled exceptions in. net

  • 2021-10-25 06:27:21
  • OfStack

Foreword:

In actual project development, we often encounter some unforeseen exceptions, and some exceptions are handled when the program is running (try)
However, some programs do not need to be processed with try in every place, so in view of this situation, we can refer to the following way to realize the unified 1 crawling processing of exceptions. The following words are not much to say, so let's take a look at the detailed introduction.

Mode 1. Page_Error handles page-level unhandled exceptions

Scope: Current. aspx page

Description: Implement Page_Error method in cs file of aspx page to listen for unhandled exceptions on current page


protected void Page_Error(object sender, EventArgs e)
  {
   string errorMsg = String.Empty;
   Exception currentError = Server.GetLastError();
   errorMsg += " Exception Handling from Pages <br />";
   errorMsg += " An error occurred in the system :<br />";
   errorMsg += " Wrong address :" + Request.Url + "<br />";
   errorMsg += " Error message :" + currentError.Message + "<br />";
   Response.Write(errorMsg);
   Server.ClearError();// Clear exception ( Otherwise, a global Application_Error Events )
  }

Mode 2. Catch unhandled exceptions through HttpModule

Scope: Global request request

Description: Implement the IHttpModule interface with one class and listen for unhandled exceptions

Implementation steps:

1. First, we need to create a new class (MyHttpModule), which needs to implement IHttpModule interface. The specific code examples are as follows:


/// <summary>
 /// MyHttpModule
 /// </summary>
 public class MyHttpModules : IHttpModule
 {
       public void Init(HttpApplication context)
  {
   context.Error += new EventHandler(context_Error);
  }

  public void context_Error(object sender, EventArgs e)
  {
   // Exceptions are handled here 
   HttpContext ctx = HttpContext.Current;
   HttpResponse response = ctx.Response;
   HttpRequest request = ctx.Request;

   // Get to HttpUnhandledException Exception, which contains the 1 Actual exceptions 
   Exception ex = ctx.Server.GetLastError();
   // Actual anomaly occurred 
   Exception iex = ex.InnerException;

   response.Write(" From ErrorModule Error handling of <br />");
   response.Write(iex.Message);

   ctx.Server.ClearError();
  }
}

2. The configuration file configures the corresponding HttpModule node

Configuration files configure HttpModule nodes in the following two ways (depending on the IIS version)

Method 1, when IIS version is below 7.0, in < system.web > Add the following configuration nodes in


<httpModules>
    <add name="MyHttpModule" type="MyHttpModule.MyHttpModules,MyHttpModule" />
</httpModules>

Method 2, when IIS version 7.0 and above, in the < system.webServer > Add the following configuration nodes in


<modules>
    <add name="MyHttpModule" type="MyHttpModule.MyHttpModules,MyHttpModule"/>
</modules>

Mode 3. Catch unhandled exceptions through Global

Scope: Global request request

Description: Listening for unhandled exceptions by implementing the Application_Error method in Global

The specific code is as follows:


void Application_Error(object sender, EventArgs e)
  {
   // Get to HttpUnhandledException Exception, which contains the 1 Actual exceptions 
   Exception ex = Server.GetLastError();
   // Actual anomaly occurred 
   Exception iex = ex.InnerException;

   string errorMsg = String.Empty;
   string particular = String.Empty;
   if (iex != null)
   {
    errorMsg = iex.Message;
    particular = iex.StackTrace;
   }
   else
   {
    errorMsg = ex.Message;
    particular = ex.StackTrace;
   }
   HttpContext.Current.Response.Write(" From Global Error handling of <br />");
   HttpContext.Current.Response.Write(errorMsg);

   Server.ClearError();// Clean up exceptions in time after processing 
  }

Summary and analysis of three kinds of abnormal grasping:

According to the order of IIS processing requests, we can know that the sequence of triggering the three methods is:

Mode 1. Page_Error Handling Page-level Unhandled Exceptions--Uncleaned Exceptions After Crawling (ClearError)-- >

Mode 2. Catch unhandled exceptions through HttpModule--uncleaned exceptions after crawling (ClearError)-- >

Mode 3. Catch unhandled exceptions through Global

The scope of the three modes is as follows: Mode 1 works on the current aspx page, and Methods 2 and 3 both work on the global

Through the above two points, so in actual use, if it is to crawl the global exception, it is recommended to adopt Mode 2

If it is an unhandled exception that crawls a 1 page, take Mode 1

Summary of processing logic after exception crawling:

After grabbing the unhandled exceptions in the program in the above three ways, what is the specific handling method in the actual project? According to my actual project application, it is summarized as follows:

{

1 The general processing logic is divided into three steps:

Step 1: Parse specific exception information

Step 2: The parsed abnormal information is put into storage (text log (convenient for subsequent problem checking)

, database log (convenient for follow-up problem checking and statistical reminder))

Step 3: Page redirection (redirect errors to customized specific custom error pages)

When redirecting, you don't need to handle the exception crawling, but you can handle it flexibly through the configuration file (see the next article for the specific implementation mode)

Do not call ClearError () to clear exceptions after exception crawling, otherwise the error redirection set by the configuration file will not work

}

Summarize


Related articles: