目 录
通过特性处理异常,也是AOP的一个功能。
定义异常处理特性AspectExceptionAttribute
该类也是继承了切面特性基类AspectAttribute
public class AspectExceptionAttribute : AspectAttribute
{
public override InterceptType InterceptType { get; set; } public override void OnEntry(AspectContext context)
{
if (context != null)
{
if (context.Result != null && context.Result is Exception)
{
Console.WriteLine("Exception : " + context.Name + " " + (context.Result as Exception).Message);
}
} } public override void OnExit(AspectContext context)
{
if (context != null)
{
Console.WriteLine("Finally : " + context.Name);
}
}
在ILGenerateProxyMethod方法中加入异常处理代码
Emit异常处理代码主要由BeginExceptionBlock,BeginCatchBlock,BeginFinallyBlock,EndExceptionBlock组成;
进行异常处理前,先申明 AspectExceptionAttribute对象,即 AspectExceptionAttribute aspectExceptionAttribute = new AspectExceptionAttribute(); 其对应Emit代码如下:
//获取异常处理类型
var aspectExceptionType = typeof(AspectExceptionAttribute); //申明一个异常处理特性对象
var aspectExceptionAttribute = il_ProxyMethod.DeclareLocal(aspectExceptionType); //获取其构造函数
ConstructorInfo temp = aspectExceptionType.GetConstructor(Type.EmptyTypes); //生成一个新对象
il_ProxyMethod.Emit(OpCodes.Newobj, temp); //存储到 aspectExceptionAttribute
il_ProxyMethod.Emit(OpCodes.Stloc, aspectExceptionAttribute);
Catch时触发aspectExceptionAttribute.OnEntry();Finally时调用 aspectExceptionAttribute.OnEixt();对应Emit代码如下:
//加载异常特性对象
2 il_ProxyMethod.Emit(OpCodes.Ldloc,aspectExceptionAttribute);
3 //加载参数
4 il_ProxyMethod.Emit(OpCodes.Ldloc, aspectContext);
5 //调用OnEntry方法
6 il_ProxyMethod.Emit(OpCodes.Callvirt, aspectExceptionType.GetMethod("OnEntry"));
Catch调用OnEntry前,还要将捕获到的Exception对象赋值给aspectContext的Result属性;即 aspectContext.Result = ex; 对应Emit代码如下:
LocalBuilder exception = il_ProxyMethod.DeclareLocal(typeof(Exception)); il_ProxyMethod.Emit(OpCodes.Stloc, exception); //复制Exception到Result
il_ProxyMethod.Emit(OpCodes.Ldloc, aspectContext); //加载AspectContext局部变量
il_ProxyMethod.Emit(OpCodes.Ldloc, exception);//错误信息
il_ProxyMethod.Emit(OpCodes.Box, typeof(Exception));
il_ProxyMethod.Emit(OpCodes.Call, typeof(AspectContext).GetMethod("set_Result"));//赋值
完整的ILGenerateProxyMethod的方法如下:
private static void ILGenerateProxyMethod(ILGenerator il_ProxyMethod, MethodInfo src_Method, Type[] paramTypes, object[] aspectAttributes)
{
int aspectCount = aspectAttributes.Length; //生成切面上下文
LocalBuilder aspectContext = CreateAspectContext(il_ProxyMethod, src_Method.Name, paramTypes); //申明临时存放切面对象和OnExit方法的变量
var aspectLocalBuilders = new LocalBuilder[aspectCount];
var onExit_Methods = new MethodInfo[aspectCount]; //获取异常处理类型
var aspectExceptionType = typeof(AspectExceptionAttribute); //申明一个异常处理特性对象
var aspectExceptionAttribute = il_ProxyMethod.DeclareLocal(aspectExceptionType); //获取其构造函数
ConstructorInfo temp = aspectExceptionType.GetConstructor(Type.EmptyTypes); //生成一个新对象
il_ProxyMethod.Emit(OpCodes.Newobj, temp); //存储到 aspectExceptionAttribute
il_ProxyMethod.Emit(OpCodes.Stloc, aspectExceptionAttribute); Label tryLabel = il_ProxyMethod.BeginExceptionBlock();//对应Try //初始化标记的切面对象,并调用切面对象的OnEntry方法
for (int i = ; i < aspectCount; i++)
{
//创建一个切面对象
var aspectType = aspectAttributes[i].GetType();
var aspect = il_ProxyMethod.DeclareLocal(aspectType);
ConstructorInfo constructor = aspectType.GetConstructor(Type.EmptyTypes); il_ProxyMethod.Emit(OpCodes.Newobj, constructor);
il_ProxyMethod.Emit(OpCodes.Stloc, aspect); var onEntry_method = aspectType.GetMethod("OnEntry");
onExit_Methods[i] = aspectType.GetMethod("OnExit"); //调用OnEntry
il_ProxyMethod.Emit(OpCodes.Ldloc, aspect);
il_ProxyMethod.Emit(OpCodes.Ldloc, aspectContext);
il_ProxyMethod.Emit(OpCodes.Callvirt, onEntry_method);
il_ProxyMethod.Emit(OpCodes.Nop); aspectLocalBuilders[i] = aspect;
} //类对象,参数值依次入栈
for (int i = ; i <= paramTypes.Length; i++)
il_ProxyMethod.Emit(OpCodes.Ldarg, i); //调用基类的方法
il_ProxyMethod.Emit(OpCodes.Call, src_Method); //定义返回值
LocalBuilder result = null; //如果有返回值,保存返回值到局部变量
if (src_Method.ReturnType != typeof(void))
{
result = il_ProxyMethod.DeclareLocal(src_Method.ReturnType);
il_ProxyMethod.Emit(OpCodes.Stloc, result); //给AspectContext的属性Result赋值
var resultSetMethod = typeof(AspectContext).GetMethod("set_Result");
il_ProxyMethod.Emit(OpCodes.Ldloc, aspectContext); //加载AspectContext局部变量
il_ProxyMethod.Emit(OpCodes.Ldloc, result);//加载返回值
il_ProxyMethod.Emit(OpCodes.Box, src_Method.ReturnType);
il_ProxyMethod.Emit(OpCodes.Call, resultSetMethod);//赋值
} //调用横切对象的OnExit方法
for (int i = ; i < aspectCount; i++)
{
il_ProxyMethod.Emit(OpCodes.Ldloc, aspectLocalBuilders[i]);
il_ProxyMethod.Emit(OpCodes.Ldloc, aspectContext);
il_ProxyMethod.Emit(OpCodes.Callvirt, onExit_Methods[i]);
il_ProxyMethod.Emit(OpCodes.Nop);
} il_ProxyMethod.BeginCatchBlock(typeof(Exception));//对应Catch //保存Exception到临时变量
LocalBuilder exception = il_ProxyMethod.DeclareLocal(typeof(Exception)); il_ProxyMethod.Emit(OpCodes.Stloc, exception); //复制Exception到Result
il_ProxyMethod.Emit(OpCodes.Ldloc, aspectContext); //加载AspectContext局部变量
il_ProxyMethod.Emit(OpCodes.Ldloc, exception);//错误信息
il_ProxyMethod.Emit(OpCodes.Box, typeof(Exception));
il_ProxyMethod.Emit(OpCodes.Call, typeof(AspectContext).GetMethod("set_Result"));//赋值 il_ProxyMethod.Emit(OpCodes.Ldloc,aspectExceptionAttribute);
il_ProxyMethod.Emit(OpCodes.Ldloc, aspectContext);
il_ProxyMethod.Emit(OpCodes.Callvirt, aspectExceptionType.GetMethod("OnEntry")); il_ProxyMethod.BeginFinallyBlock(); //对应Finally il_ProxyMethod.Emit(OpCodes.Ldloc, aspectExceptionAttribute);
il_ProxyMethod.Emit(OpCodes.Ldloc, aspectContext);
il_ProxyMethod.Emit(OpCodes.Callvirt, aspectExceptionType.GetMethod("OnExit")); il_ProxyMethod.EndExceptionBlock(); //异常处理结束 //如果有返回值,则把返回值压栈
if (result != null)
il_ProxyMethod.Emit(OpCodes.Ldloc, result); il_ProxyMethod.Emit(OpCodes.Ret);//返回
}
以 NYearLater 为例反编译后的代码如下:
public override int NYearLater(int num)
{
AspectContext aspectContext = new AspectContext(this, "NYearLater", new object[]
{
num
});
AspectExceptionAttribute aspectExceptionAttribute = new AspectExceptionAttribute();
int num2;
try
{
LogAttribute logAttribute = new LogAttribute();
logAttribute.OnEntry(aspectContext);
num2 = base.NYearLater(num);
aspectContext.Result = num2;
logAttribute.OnExit(aspectContext);
}
catch (Exception ex)
{
aspectContext.Result = ex;
aspectExceptionAttribute.OnEntry(aspectContext);
}
finally
{
aspectExceptionAttribute.OnExit(aspectContext);
}
return num2;
}
测试
修改 NYearLater方法:如果大于200了抛出异常
public virtual int NYearLater(int a)
{
int larter = Age + a; if (larter > )
{
throw new Exception("Too Old!");
} return larter;
}
修改测试方法:
public static void Test()
{
try
{
AopTest WithPara = DynamicProxy.Create<AopTest>("lxl", ); ; WithPara.NYearLater(); Console.WriteLine("done..."); }
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
运行结果:
Log OnEntry:set_Name(lxl)
Log OnExit: set_Name Finally : set_Name
Log OnEntry:set_Age()
Log OnExit: set_Age Finally : set_Age
Log OnEntry:NYearLater() //以310调用方法
Log OnEntry:get_Age()
Log OnExit: get_Age Result: Finally : get_Age Exception : NYearLater Too Old! //捕获异常 Finally : NYearLater
done...
可以看到异常处理完成。