在PostSharp中得OnExceptionAspect类是针对异常的消息截取。继承于它的特性将可以在发生异常的时候对方法体内的异常截取,并且做出动作,看是否停止本程序运行,还是忽略异常。

这个类里面有两个主要的函数可以重载分别是OnException(MethodExecutionArgs args)、GetExceptionType(System.Reflection.MethodBase targetMethod)。他们分别意义如下:

OnException(MethodExecutionArgs args):当发生异常时截取异常发生的位置(在哪个命名空间?哪个类?哪个方法?)、异常类型、异常消息等信息,并且可以异常将如何处理。

GetExceptionType(System.Reflection.MethodBase targetMethod):设置需要拦截的异常类型,比如设置需要拦截参数异常,那么其他的异常类型发生时将不会被此特性所拦截。

首先我们编写一个继承于OnExceptionAspect类的特性,并且重载相关函数如下代码:

[Serializable]publicclassExceptionAttribute:OnExceptionAspect{//当异常发生时publicoverridevoidOnException(MethodExecutionArgsargs){Console.WriteLine("______________________________________________________________________________");Console.WriteLine("异常时间:"+DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss.fff"));;Console.WriteLine("异常类名:"+args.Method.DeclaringType.FullName);Console.WriteLine("异常方法:"+args.Method.Name);Console.WriteLine("异常信息:"+args.Exception.ToString());args.FlowBehavior=FlowBehavior.Continue;}//需要拦截的异常类型为ArgumentExceptionpublicoverrideTypeGetExceptionType(System.Reflection.MethodBasetargetMethod){returntypeof(ArgumentException);}}

其次我们编写一个目标类,此类中含有一个方法,方法内抛出参数异常,并为其添加Exception的特性,如以下代码所示:

classPeople{[Exception]publicvoidTest(inta,intb){thrownewArgumentException("这里有参数错误,请检查参数");}}

再编写一个对比目标类,要实现同样的效果需要远远多于我们使用PostSharp的情况,而且会让我们的逻辑处理更为复杂和麻烦,如下代码所示:

classPelple1{publicvoidTest(inta,intb){try{thrownewArgumentException("这里有参数错误,请检查参数");}catch(ArgumentExceptionargs){Console.WriteLine("______________________________________________________________________________");Console.WriteLine("异常时间:"+DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss.fff"));;Console.WriteLine("异常信息:"+args.ToString());}}}

最后我们在客户端初始化People类并且引用方法如下代码:

classProgram{staticvoidMain(string[]args){Peoplep=newPeople();p.Test(3,5);Pelple1p1=newPelple1();p1.Test(3,5);Console.ReadLine();}}

如需源码请点击 PostSharpOnExceptionAspect.zip 下载,运行效果如下图: