Skip to content

Instantly share code, notes, and snippets.

@akimboyko
Created January 4, 2013 21:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akimboyko/4457261 to your computer and use it in GitHub Desktop.
Save akimboyko/4457261 to your computer and use it in GitHub Desktop.
AOP: handwritten tracing decorator
void Main()
{
TraceDecorator.Aspect(() => StaticLogic.SuccessfulCall());
TraceDecorator.Aspect(() => StaticLogic.ExceptionCall());
TraceDecorator.Aspect(() => StaticLogic.SuccessfulCallWithReturn(42)).Dump();
TraceDecorator.Aspect(() => StaticLogic.ExceptionCallWithReturn(42)).Dump();
}
public static class TraceDecorator
{
public static T Aspect<T>(Func<T> func)
{
try
{
return func();
}
catch(Exception ex)
{
LogException(ex);
return default(T);
}
}
public static void Aspect(Action func)
{
try
{
func();
}
catch(Exception ex)
{
LogException(ex);
}
}
private static void LogException(Exception ex)
{
Console.WriteLine("Traced by TraceDecorator: {0}", ex);
}
}
public static class StaticLogic
{
public static void SuccessfulCall()
{
}
public static void ExceptionCall()
{
throw new Exception();
}
public static string SuccessfulCallWithReturn(int input)
{
return string.Format("ok: input {0}", input);
}
public static string ExceptionCallWithReturn(int input)
{
throw new Exception();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment