I've been dizzy writing ASP.NET for the past two days, and I always want to be lazy. Since almost every method in the background code requires try..catch, it feels very cumbersome. It also reminds me of AOP, but the method of AOP is relatively complicated and there are many methods. For example, use Dynamic Proxy, Attribute, or Emit, etc. I suddenly thought of the new feature of C# 2.0, anonymous delegation, and thought it was a bit ugly. . . However, in fact, you can also simply simulate the effect of AOP in a relatively lightweight way:
// The requirement to force a page base class in asp.net is not excessive. . .
public partial class TestLogger: PageBase {
protected void Page_Load(object sender, EventArgs e) {
// This method is implemented in the page base class, and general exception handling, logging logic, etc. can be implemented in it.
TryDo(
// This is where the actual things are done
delegate() {
int a = 1;
int b = 0;
int c = a / b;
},
// This is an optional exception handling. If you pass null, the exception will be simply ignored.
delegate() {
Response.Write("Sorry, an error occurred.");
}
);
}
}
The implementation code in the page base class is very simple, and it can also be easily and uniformly managed. Here I assume that I simply use log4net to log exceptions:
using System;
using System.Web.UI;
using log4net;
namespace SomeNamespace {
//Define a simple delegate for passing anonymous delegates
public delegate void MyAction();
//Define page base class
public class PageBase : Page {
protected ILog logger;
// All exception handling logic is handled centrally in the page base class.
protected void TryDo(MyAction doHandler, MyAction exceptHandler) {
try {
// Do something practical
doHandler();
} catch (Exception ex) {
//Simple exception logging
logger.Error(ex);
// Some other processing
// . . .
// Call custom exception handling, no specific information of Exception is returned here. Because there is no need to show it to the user anyway. . .
if (exceptHandler != null)
exceptHandler();
}
}
protected override void OnInit(EventArgs e) {
// Initialize logger. Just here GetType() can get the actual type of the subclass
logger = LogManager.GetLogger(this.GetType());
base.OnInit(e);
}
}
}
Okay, let’s stop writing here. This is just a simple idea of mine. The purpose is to implement centralized management of exceptions or logs in a lightweight manner. Of course, this is incomparable with the complete AOP concept, but having said that, it seems that there is currently no perfect AOP framework in .NET.
http://www.cnblogs.com/RChen/archive/2006/11/16/aspnet_exception_handling.html