Three ways to catch global unhandled exception in. Net

Time:2019-12-13

Preface:

In the actual project development, we often encounter some unforeseen exceptions, some of which are handled (try) when the program is running
However, some programs don’t need to use try to handle every place. In this case, you can refer to the following methods to realize unified exception grabbing. I won’t say much next. Let’s have a look at the detailed introduction.

Method 1. Page error handles page level unhandled exceptions

Scope: current. ASPX page

Description: in the CS file of the ASPX page to be processed, the page ﹣ error method is implemented to listen for the unhandled exceptions of the current page

protected void Page_Error(object sender, EventArgs e)
  {
   string errorMsg = String.Empty;
   Exception currentError = Server.GetLastError();
   Errormsg + = "exception handling from page < br / >";
   Errormsg + = "system error: < br / >";
   Errormsg + = "error address:" + request. URL + "< br / >;
   Errormsg + = "error message:" + currenterror. Message + "< br / >;
   Response.Write(errorMsg);
   Server. Clearerror(); // clear the exception (otherwise the global application error event will be raised)
  }

Mode 2: catch the unhandled exception through HttpModule

Scope: Global request

Description: implements the ihttpmodule interface through a class and listens for unhandled exceptions

Implementation steps:

1. First, you need to create a new class (myhttpmodule), which needs to implement the 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)
  {
   //Handle exception here
   HttpContext ctx = HttpContext.Current;
   HttpResponse response = ctx.Response;
   HttpRequest request = ctx.Request;

   //Get httpunhandledexception exception, which contains an actual exception
   Exception ex = ctx.Server.GetLastError();
   //Actual exception
   Exception iex = ex.InnerException;

   Response. Write ("error handling from errormodule < br / >");
   response.Write(iex.Message);

   ctx.Server.ClearError();
  }
}

2. Configure the corresponding HttpModule node in the configuration file

There are two ways to configure the HttpModule node in a profile (depending on the IIS version)

Method 1. When the IIS version is below 7.0, add the following configuration node in < system. Web >


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

Method 2. When IIS version is 7.0 or above, add the following configuration nodes in < system. Webserver >


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

Mode 3: capture the unhandled exception in global

Scope: Global request

Description: to listen 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 httpunhandledexception exception, which contains an actual exception
   Exception ex = Server.GetLastError();
   //Actual exception
   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 ("error handling from global < br / >");
   HttpContext.Current.Response.Write(errorMsg);

   Server. Clearerror(); // clear exceptions in time after processing
  }

Summary and analysis of three kinds of abnormal grabs:

According to the order in which IIS processes requests, we can know that the order in which the three methods are triggered is:

Method 1: page_error handles page level unhandled exceptions — clear error after fetching — >

Mode 2: use HttpModule to catch the unhandled exception — clear error after grabbing — >

Mode 3: capture the unhandled exception in global

The scope of the three methods is: Method 1 works on the current ASPX page, method 2 and method 3 both work on the overall situation

Through the above two points, so in actual use, if it is to grab the global but not out of the exception, it is recommended to use method 2

If it is to grab an unhandled exception of a page, use method 1

Summary of handling logic after exception grabbing:

After the unhandled exceptions in the program captured by the above three methods, what are the specific handling methods in the actual project? According to the actual application of the project, it is summarized as follows:

  {

The general processing logic consists of three steps:

Step 1: analyze specific exception information

Step 2: the parsed exception information is put into storage (text log (convenient for subsequent query)

. database log (convenient for follow-up query and statistical reminder)

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

When redirecting, it does not need to be handled when the exception is fetched, but it can be handled flexibly through the configuration file (see the next chapter for the specific implementation method)

After exception fetching, do not call clearerror() to clear the exception, otherwise error redirection set by the configuration file will not work

  }

summary

The above is the whole content of this article. I hope that the content of this article has a certain reference learning value for everyone’s study or work. If you have any questions, you can leave a message and exchange. Thank you for your support for developepaar.