[Serializable]
public class MyAspect: OnExceptionAspect
{
public override void OnException(MethodExecutionArgs args)
{
throw new MyCustomException(args.Exception);
}
}
public class MyCustomException : Exception
{
public override string StackTrace
{
get
{
//return new StackTrace(10).ToString(); //Skip frames
return string.Empty; //Return empty string
}
}
}
You actually have to throw a NEW exception. @Ani's example will simply rethrow the exception already thrown with the same stack trace (it's the same because of how you got to the aspect). Throwing a new exception will "change" the stack trace but it won't erase it. If you want to erase it, you will need to throw your own class that overrides the stack trace property. passing in the old exception to the new exception will make the old exception the inner exception (if you want that)
You can accomplish this with and without PostSharp. The key is your custom exception class.
Given the following code
class Program
{
static void Main(string[] args)
{
try
{
Test1();
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace + Environment.NewLine);
}
Console.ReadKey();
}
private static void Test1()
{
try
{
Test2();
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace + Environment.NewLine);
throw e;
}
}
private static void Test2()
{
try
{
Test3();
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace + Environment.NewLine);
throw;
}
}
[MyAspect]
private static void Test3()
{
throw new InvalidOperationException();
}
}
[Serializable]
public class MyAspect : OnExceptionAspect
{
public override void OnException(MethodExecutionArgs args)
{
throw args.Exception;
}
}
the output is
at ConsoleApplication5.MyAspect.OnException(MethodExecutionArgs
args) in C:\T est\Program.cs:line 69 at
ConsoleApplication5.Program.Test3() in C:\Test\Program.cs:line 59
at ConsoleApplication5.Program.Test2() in C:\Test\Program.cs:line 47
at ConsoleApplication5.MyAspect.OnException(MethodExecutionArgs
args) in C:\T est\Program.cs:line 69 at
ConsoleApplication5.Program.Test3() in C:\Test\Program.cs:line 59
at ConsoleApplication5.Program.Test2() in C:\Test\Program.cs:line 52
at ConsoleApplication5.Program.Test1() in C:\Test\Program.cs:line 34
at ConsoleApplication5.Program.Test1() in C:\Test\Program.cs:line
39 at ConsoleApplication5.Program.Main(String[] args) in
C:\Test\Program.cs:line 19