1. Capture unprocessed exceptions using HttpModule [recommended]
First, you need to define an HttpModule and listen for unprocessed exceptions. The Code is as follows:
Public void Init (HttpApplication context) {context. error + = new EventHandler (context_Error);} public void context_Error (object sender, EventArgs e) {// Exception Handling HttpContext ctx = HttpContext. current; HttpResponse response = ctx. response; HttpRequest request = ctx. request; // get the HttpUnhandledException Exception. This Exception contains an actual Exception, ex = ctx. server. getLastError (); // Exception iex = ex. innerException; response. write ("error handling from ErrorModule <br/>"); response. write (iex. message); ctx. server. clearError ();}
Then add the configuration information in web. config:
In this way, you can process the exceptions not handled in the webApp.
This method is recommended because it is easy to expand and universal. This method is also the most used.
2. Capture unprocessed exceptions in Global
There is an Application_Error method in Global. asax. This method is called when an unhandled exception occurs in the application. We can add the processing code here:
Void Application_Error (object sender, EventArgs e) {// gets the HttpUnhandledException Exception. This Exception contains an actual Exception. ex = Server. getLastError (); // Exception iex = ex. innerException; string errorMsg = String. empty; string particle = String. empty; if (iex! = Null) {errorMsg = iex. message; particle = iex. stackTrace;} else {errorMsg = ex. message; particle = ex. stackTrace;} HttpContext. current. response. write ("error handling from Global <br/>"); HttpContext. current. response. write (errorMsg); Server. clearError (); // clear exceptions in time after handling}
This method can also obtain the global unhandled exceptions. However, compared with the implementation of HttpModule, It is not flexible and general.
HttpModule takes precedence over Application_Error in Global.
3. Page-level exception capture
You can also add an exception handling method to the page: add the Page_Error Method to the Code on the page, which will process the unprocessed exception information on the 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, a global Application_Error event will be thrown )}
This method takes precedence over HttpModule and Global.