我有一个 multicast OnExceptionAspect来自 Postsharp它应用于装配级别。这自然意味着所有方法在抛出异常时都会调用方面。
在 Aspect 中,我正在记录异常详细信息包括异常发生时传递的参数值,这是正常工作的。
但是,因为这适用于程序集中的所有方法,所以当异常在每个方法中冒泡时,都会为堆栈中的每个方法创建一个日志条目。
我不知道如何防止这种情况发生,最初我打算比较异常(看看它是否相同),但这看起来很乱。以前一定有人遇到过这个问题,有什么想法吗?
最佳答案
这个问题有两种解决方案。
一个。使用线程静态字段存储任何已记录的异常。
[Serializable]
public class MyAspect : OnExceptionAspect
{
[ThreadStatic]
private static Exception lastException;
public override void OnException(MethodExecutionArgs args)
{
if(args.Exception != lastException)
{
string msg = string.Format("{0} had an error @ {1}: {2}\n{3}",
args.Method.Name, DateTime.Now,
args.Exception.Message, args.Exception.StackTrace);
Trace.WriteLine(msg);
lastException = args.Exception;
}
}
}
B.向 Exception 对象添加标记。
[Serializable]
public class MyAspect : OnExceptionAspect
{
private static object marker = new object();
public override void OnException(MethodExecutionArgs args)
{
if(!args.Exception.Data.Contains(marker))
{
string msg = string.Format("{0} had an error @ {1}: {2}\n{3}",
args.Method.Name, DateTime.Now,
args.Exception.Message, args.Exception.StackTrace);
Trace.WriteLine(msg);
args.Exception.Data.Add(marker, marker);
}
}
}
关于c# - 多播 OnExceptionAspect 正在记录冒泡异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10314133/