I want to get to MyExceptionAspect.OnException
when an exception is thrown from MyInterceptorAspect.OnInvoke
so the following code will return "Much love":
public class MyClass
{
[MyInterceptorAspect]
[MyExceptionAspect]
public string Do()
{
return "LOVE";
}
}
[Serializable]
public sealed class MyInterceptorAspect : MethodInterceptionAspect
{
public override void OnInvoke(MethodInterceptionArgs args)
{
// ...
throw new Exception("Much love");
// ...
// base.OnInvoke(args) is NOT called.
}
}
[Serializable]
public sealed class MyExceptionAspect : OnExceptionAspect
{
public override void OnException(MethodExecutionArgs args)
{
args.ReturnValue = args.Exception.Message;
args.FlowBehavior = FlowBehavior.Return;
}
}
At runtime, when the exception is thrown from the interceptor, it's not caught by OnExceptionAspect
.
Figured it out while writing the question :)
In compile-time, PostSharp uses OnExceptionAspect
to wrap the Do
method with try-catch, and insert a call for MethodInterceptionAspect.OnInvoke
on the first line of it - so the order of the aspects matter to the fact if that call will be included in the try
block.
So this change solved it nicely:
public class MyClass
{
[MyExceptionAspect(AspectPriority = 1)]
[MyInterceptorAspect(AspectPriority = 2)]
public string Do()
{
return "LOVE";
}
}