asp.net
These two days write asp.net write dizzy, old want to steal a bit lazy. Because in the background of the code in almost every method to try ... Catch so come over, feel very cumbersome. It is also associated with AOP, but the approach of AOP is relatively complex and much more so. such as Dynamic Proxy, Attribute, or Emit. I suddenly associate with the new features of C # 2.0 anonymous delegate, feel this although ugly ... But you can actually compare the lightweight, simple simulation of AOP:
ASP.net inside the mandatory to do a page base class requirements is not excessive ...
Public partial class Testlogger:pagebase {
protected void Page_Load (object sender, EventArgs e) {
This method is implemented in the base class of the page, which can implement common exception handling, log logic and so on.
Trydo (
It's the actual thing inside.
Delegate () {
int a = 1;
int b = 0;
int c = A/b;
},
This is an optional exception handling, and if you pass a null, you simply ignore the exception
Delegate () {
Response.Write ("Sorry, an error has occurred.") ");
}
);
}
}
In the page base class inside the implementation code is very simple, can also facilitate the unified management. Here I assume that simply using log4net to log the exception:
Using System;
Using System.Web.UI;
Using Log4net;
Namespace SomeNamespace {
Defines a simple delegate for passing anonymous delegates
public delegate void Myaction ();
Define a page base class
public class Pagebase:page {
protected ILog Logger;
The page base class concentrates on all exception handling logic
protected void Trydo (Myaction dohandler, myaction excepthandler) {
try {
Do something practical.
Dohandler ();
catch (Exception ex) {
Simple record exception
Logger. Error (ex);
Some other processing
。。。
Calls the custom exception handling, there is no specific information to return Exception. Because anyway no need to show the user ...
if (Excepthandler!= null)
Excepthandler ();
}
}
protected override void OnInit (EventArgs e) {
Initialize logger. Right here GetType () can take the actual type of the subclass
Logger = Logmanager.getlogger (this. GetType ());
Base. OnInit (e);
}
}
}
All right, let's write this down. This is just a simple idea of mine. Objective to achieve centralized management of the lightweight implementations of exceptions or logs. Of course, this is not comparable to the complete AOP concept, but it seems that there is no perfect AOP framework in. NET yet.