In the actual development process, an application system should have its own mature Exception Handling framework. In this way, a unified handling style can be obtained when exceptions occur, elegantly feedback exception information to developers and users. We all know that ,. net exception handling is based on the "exception chain" method from the underlying layer to the high-level layer. If you cannot determine the exception boundary as early as possible and capture the exception, the CLR will automatically help us handle the exception, however, the system overhead is very large, so an important principle for exception handling is "early detection, early throw, and early processing ". However, the server-side common capture Exception Processing summarized in this article can be broadly considered as an operation at the performance Layer. To capture specific exceptions at a specific layer, it is not covered in the discussion.
1. basepage class Processing Method
Override the onerror event in the public base class of the page. In this articleArticleIn, Lou pig has been pastedCode. Based on experience, many people write this almost during development, and it is helpful for debugging and maintenance. It must be noted that each new page must be inherited from the basepage class for exception handling.
2. Global. asax Processing Method
As described in 1, The basepage class exception handling requires that each aspx class file inherit from it, and the applicability and performance are obviously compromised. The global. asax file defines the Asp.net application.ProgramThe methods, attributes, and events that are common to all application objects in. We can implement and process application_error events in global. asax without using basepage. The following describes how to handle exceptions in the basepage class:
Code
/// <Summary>
/// Error Handling: Write logs and navigate to the public error page.
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "E"> </param>
Protected Void Application_error ( Object Sender, eventargs E)
{
If (server. getlasterror () = NULL) return;
Exception ex = Server. getlasterror (). getbaseexception ();
String Error = This . Dealexception (Ex );
DOTNET. Common. util. Logger. writefilelog (error, httpcontext. Current. Request. physicalapplicationpath + " Logfile " );
If (EX. innerexception ! = Null )
{
Error = This . Dealexception (Ex );
DOTNET. Common. util. Logger. writefilelog (error, httpcontext. Current. Request. physicalapplicationpath + " Logfile " );
}
This . Server. clearerror ();
This . Response. Redirect ( " /Error. aspx " );
}
/// <Summary>
/// Exception Handling, used to write main exception information to text logs
/// </Summary>
/// <Param name = "ex"> </param>
/// <Returns> </returns>
Private String Dealexception (exception ex)
{
This . Application [ " Stacktrace " ] = Ex. stacktrace;
This . Application [ " Messageerror " ] = Ex. message;
This . Application [ " Sourceerror " ] = Ex. source;
This . Application [ " Targetsite " ] = Ex. targetsite. tostring ();
String Error = String . Format ( " URL: {0} \ n: {1} \ n error message: {2} \ n error Stack: {3} \ n " ,
This . Request. rawurl, Ex. targetsite, Ex. Message, Ex. stacktrace );
Return Error;
}
The advantage of the above method is that when you write code once, most of the exceptions that occur in the application will be captured and handled for you. Lou pig would like to express his heartfelt feelings here. Thanks to MS for providing us with such an excellent framework, it is too easy.
3. ihttpmodule interface processing
The Processing Methods of steps 1 and 2 are very familiar to everyone. Lou pig basically follows the above two methods in actual development, in addition, Lou pig was excited to thank Ms for the handling of the food in the middle of 2. However, when the Asp.net program calls a thread for asynchronous processing, exceptions that are easily thrown in the background thread or thread pool cannot be completely caught by 1 or (and) 2, this involves processing exceptions not captured in Asp.net. That is to say, the exception handling is incomplete in many large and small projects that Lou pig has previously done. Is it because the NC building has not thanked the country for the evil consequences? Thanks to the country, Ms, blog, xdjm, and myself ......
The process for uncaptured exceptions in Asp.net is as follows:
(1) create a class that implements the ihttpmodule Interface
Code
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. webcontrols;
Using System. text;
NamespaceDOTNET. Common. webform
{
UsingDOTNET. Common. util;
/// <Summary>
/// Common uncaptured Exception Handling
/// </Summary>
Public Class Aspnetunhandledexceptionmodule: ihttpmodule
{
Static Object Syncobj = New Object ();
Static Bool Isinit = False ;
PublicAspnetunhandledexceptionmodule ()
{
}
# RegionIhttpmodule Methods
Public Void Init (httpapplication context)
{
Lock (Syncobj)
{
If ( ! Isinit)
{
Appdomain. currentdomain. unhandledexception + = New Unhandledexceptioneventhandler (onunhandledexception );
Isinit = True ;
}
}
}
Public VoidDispose ()
{
}
# Endregion
# RegionOnunhandledexception
Void Onunhandledexception ( Object O, unhandledexceptioneventargs E)
{
If (E. exceptionobject = Null ) Return ;
Exception ex = E. predictionobject As Exception;
String Error = String . Format ( " Exception thrown: {0} \ n error message: {1} \ n error Stack: {2} \ n " ,
Ex. targetsite, Ex. Message, Ex. stacktrace );
Logger. writefilelog (error, appdomain. currentdomain. basedirectory + " Logfile " );
}
# Endregion
}
}
(2) web. config node configuration
< Httpmodules >
< Add Name = "Aspnetunhandledexceptionmodule" Type = "DOTNET. Common. webform. aspnetunhandledexceptionmodule, DOTNET. Common. webform" > </ Add >
</ Httpmodules >
Finally, paste the test code:
Code
Protected Void Page_load ( Object Sender, eventargs E)
{
If ( ! Ispostback)
{
System. Threading. threadpool. queueuserworkitem ( New System. Threading. waitcallback (test ), Null );
}
}
Protected Void Test ( Object State)
{
Int [] Numarr = New Int [ 100 ];
Numarr [ 100 ] = 100 ; // Exception
}
It should be noted that, in case of exceptions, each thread has its own independent context, therefore, the httpcontext object should appear in the exception handling stage as little as possible.
Summary: I don't know how many children's shoes think that exception handling is to try... catch in the code, throw an exception and complete it? If there is one, haha, Lou pig comforted himself with the phrase "no one is born to be perfect. Of course, try... catch does not mean no. It only means that we are too hasty in dealing with exceptions. In order to show our professionalism and comprehensiveness, please refer to other articles about Exception Handling. Compared with the core idea of exception handling (the "Big intelligence" of exception handling "), the summary in this article ("Tips" for exception handling) may also be misleading for beginners. Be sure to check carefully.
Demo download: Demo