views:

131

answers:

2

I would like to automagically add the following code around the body of some methods:

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

I am working with PostSharp 1.0 and this is what I've done at the moment:

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

My problem is that I can see the PostSharp OnException call in the stack.
What would be the good practice to avoid this and get the same call stack as implementing by hand the exception handler?

+2  A: 

There is no way to hide "OnException" from the call stack.

Gael Fraiteur
This was not an expected answer, but it is the most acurate one! Thanks.
remio
+1  A: 

Two things working in tandem will allow you to do this:

  1. The fact that Exception.StackTrace is virtual
  2. The use of the skipFrames parameter to the StackFrame constructor. This is not required, but makes things easier

The below example demonstrates how to customize the stack trace. Note that I know of no way to customize the Exception.TargetSite property, which still gives the details of the method from which the exception originated.

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

HTH,
Kent

Kent Boogaart
This is not 100% clean (TargetSite), but I like the hack. Thanks.
remio