0

我想在一些方法的主体周围自动添加以下代码:

try
{
   // method body
}
catch (Exception e)
{
   throw new MyException("Some appropriate message", e);
}

我正在使用 PostSharp 1.0,这就是我目前所做的:

public override void OnException(MethodExecutionEventArgs eventArgs)
{
    throw new MyException("Some appropriate message", eventArgs.Exception);
}

我的问题是我可以OnException在堆栈中看到 PostSharp 调用。
避免这种情况并获得与手动实现异常处理程序相同的调用堆栈的良好做法是什么?

4

2 回答 2

2

无法从调用堆栈中隐藏“OnException”。

于 2009-11-18T11:05:52.750 回答
1

两件事协同工作将允许您执行此操作:

  1. 事实Exception.StackTracevirtual
  2. 对构造函数的skipFrames参数的使用。StackFrame这不是必需的,但会使事情变得更容易

下面的示例演示了如何自定义堆栈跟踪。请注意,我不知道如何自定义该Exception.TargetSite属性,它仍然提供了引发异常的方法的详细信息。

using System;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // exception is reported at method A, even though it is thrown by method B
            MethodA();
        }

        private static void MethodA()
        {
            MethodB();
        }

        private static void MethodB()
        {
            throw new MyException();
        }
    }

    public class MyException : Exception
    {
        private readonly string _stackTrace;

        public MyException()
        {
            // skip the top two frames, which would be this constructor and whoever called us
            _stackTrace = new StackTrace(2).ToString();
        }

        public override string StackTrace
        {
            get { return _stackTrace; }
        }
    }
}
于 2009-11-18T19:59:45.397 回答