【问题标题】:How to convert an exception to another one using PostSharp?如何使用 PostSharp 将异常转换为另一个异常?
【发布时间】:2011-09-28 00:44:21
【问题描述】:

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

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);
}

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

【问题讨论】:

    标签: c# exception exception-handling aop postsharp


    【解决方案1】:

    没有办法从调用堆栈中隐藏“OnException”。

    【讨论】:

    • 这不是预期的答案,但它是最准确的答案!谢谢。
    【解决方案2】:

    两件事情协同工作可以让你做到这一点:

    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; }
            }
        }
    }
    

    【讨论】:

    • 这不是 100% 干净的 (TargetSite),但我喜欢这个 hack。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 1970-01-01
    • 2016-08-20
    • 2012-08-23
    • 2014-10-06
    • 2023-02-24
    相关资源
    最近更新 更多