I am looking into using post sharp and I am trying to put together a few demos. One of them was an aspect that will log exceptions, and another was to check for null arguments and throw an exception when one is encountered.
The problem I am having is that I want my exception logging aspect to log the exceptions thrown by the null checking aspect. It doesn't seem to be working. Does anybody know of a way to make this work?
EDIT:To be clear, the exception logger is working with exceptions that are thrown outside of an aspect, but isnt logging the exceptions thown on the NullCheckAttribute
The code for the null checking aspect is as follows
[Serializable]
public class NullCheckAttribute : OnMethodBoundaryAspect
{
[ExceptionLogger]
public override void OnEntry(MethodExecutionArgs args)
{
foreach (var argument in args.Arguments)
{
if (argument == null)
throw new InvalidOperationException("Null argument in " + args.Method.Name);
}
}
}
And the code for the exception logger
[Serializable]
public class ExceptionLoggerAttribute : OnMethodBoundaryAspect
{
public override void OnException(MethodExecutionArgs args)
{
Console.WriteLine("Exception thrown in " + args.Method.Name);
Console.WriteLine("***Message: " + args.Exception.Message);
Console.WriteLine("***Stack trace: " + args.Exception.StackTrace);
}
}
I should also mention that I am simply using a free licence for this.
PostSharp doesn't allow you to apply aspects on an aspect class, which is what you're trying to do by applying [ExceptionLogger]
in NullCheckAttribute
class.
Currently, if an aspect attribute is detected on an aspect class, then it is silently ignored. It behaves this way because most of the time this application is unintentional (through multicasting).
The correct way to achieve the desired effect (log the exception thrown by the null check) is to apply both attributes to the target method. Also, keep in mind that the order of the applied attributes matters. If you change it for this example, then you won't see your log message - because the null check will be executed before the try/catch introduced by the exception logger.
[ExceptionLogger(AspectPriority = 1)]
[NullCheck(AspectPriority = 2)]
private void TestMethod(string s)
{
Console.WriteLine(s);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With