|
5.异常处理链 ExceptionSink.这里实现异常处理,和异常记录功能.主要是对IMethodReturnMessage进行包装,达到处理目的. public override IMessage SyncWrapProcessMessage(IMessage msg, IMethodReturnMessage returnMsg)
...{
MethodReturnMessageWrapper wrapMsg = new MethodReturnMessageWrapper(returnMsg);
if(wrapMsg.Exception != null)
...{
wrapMsg.Exception = null;
object[] logAttribute = returnMsg.MethodBase.GetCustomAttributes(typeof(ExceptionAttribute),true);
if(logAttribute.Length == 0)
logAttribute = returnMsg.MethodBase.DeclaringType.GetCustomAttributes(typeof(ExceptionAttribute),true);
wrapMsg.ReturnValue = (logAttribute[0] as ExceptionAttribute).ReturnValue;
}
return wrapMsg;
}
(四)Aop异常管理调用测试
1.需要异常管理的类,此处为CalculateTest,它继承ContextBoundObject而来,上有[ExceptionAttribute]约束,代码接受异常管理,默认异常处理后返回null,下面方法public string CalculateLog(int a)则加标签[ExceptionAttribute("I Love You to")]表示,此处覆盖类定义,异常处理后返回的是"I Love You".[ExceptionAttribute(123456789)]异常则返回123456789
[ExceptionAttribute]
public class CalculateTest : AspectObject
...{
[ExceptionAttribute("I Love You to")]
public string CalculateLog(int a)
...{
//Thread.Sleep(5000);
throw new ArgumentOutOfRangeException();
return Convert.ToString(checked(a*a));
} public object CalculateLog(int a,int b)
...{
//Thread.Sleep(5000);
throw new ArgumentException();
return checked(a / b);
} [ExceptionAttribute(123456789)]
public int CalculateLog(int a,int b,int c)
...{
//Thread.Sleep(5000);
throw new ArithmeticException();
return checked(a+b+c);
} public DataSet TestForDataSet(string tableName)
...{
//Thread.Sleep(5000);
DataSet ds = new DataSet(tableName);
throw new ConstraintException();
return ds;
}
}
2.测试类
static void Main(string[] args)
...{
CalculateTest cls = new CalculateTest();
object result0 = cls.CalculateLog(1,2);
if(result0 != null)
Console.WriteLine("cls.CalculateLog(1,2)的返回值是:"+result0);
else
Console.WriteLine("cls.CalculateLog(1,2)的返回值是:"+"null");
Console.WriteLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); int result1 = cls.CalculateLog(1,2,3);
Console.WriteLine("cls.CalculateLog(1,2,3)的返回值是:"+result1);
Console.WriteLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); string result2 = cls.CalculateLog(1);
Console.WriteLine("cls.CalculateLog(1)的返回值是:"+result2);
Console.WriteLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); DataSet ds = cls.TestForDataSet("THIS IS A NULL TABLE");
if(ds != null)
Console.WriteLine("cls.TestForDataSet(\"THIS IS A NULL TABLE\")的返回值是:"+ds.DataSetName);
else
Console.WriteLine("cls.TestForDataSet(\"THIS IS A NULL TABLE\")的返回值是:"+"null");
Console.WriteLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
Console.ReadLine(); }
3.最终结果如下图,成功记录了方法调用之前的信息,异常出现的信息,异常处理后返回的值信息,处理之后的其它信息.
以上这些就是基础的实现了,还等什么呢 把代码DOWN下去自己编译运行一下, 在类ClassTest加个断点一步一步的调试一下,什么都明白了.以后工作中的异常是不是就可以归Aop处理了呢?
点击此处下载代码: AOP异常处理
|