Skip to content

Instantly share code, notes, and snippets.

@squadwuschel
Created March 4, 2016 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save squadwuschel/7d3b954aa96256f6b27e to your computer and use it in GitHub Desktop.
Save squadwuschel/7d3b954aa96256f6b27e to your computer and use it in GitHub Desktop.
PostSharp - OnExceptionAspect
[Serializable]
public class LoggerAspect : OnExceptionAspect
{
private static ILog logger = LogManager.GetLogger("MeinLogger");
//Meldung die Angezeigt werden soll
private string ExceptionMessage { get; set; }
private Type HandleThisExceptionType { get; set; }
public LoggerAspect(string exceptionMessage, Type handleThisExceptionType = null)
{
ExceptionMessage = exceptionMessage;
HandleThisExceptionType = handleThisExceptionType;
}
public override Type GetExceptionType(MethodBase targetMethod)
{
//Den von uns übergebenen ExceptionType abfangen.
if (this.HandleThisExceptionType != null)
{
return this.HandleThisExceptionType;
}
//Sonst wird nur NotImplemented Exception abgefangen.
return typeof (NotImplementedException);
}
public override void OnException(MethodExecutionArgs args)
{
logger.Info(ExceptionMessage, args.Exception);
args.FlowBehavior = FlowBehavior.Return;
//Den Typ der Aufrufenden Methode ermitteln
var info = (MethodInfo)args.Method;
//Eine Instanz der Methode erstellen und z.b. einen Parameter übergeben
args.ReturnValue = Activator.CreateInstance(info.ReturnType, "SquadWuschel");
}
}
static void Main(string[] args)
{
var person = GetPerson();
Console.WriteLine(person.Name);
Console.ReadLine();
}
[LoggerAspect("Es ist ein Fehler aufgetreten.", typeof(Exception))]
public static Person GetPerson()
{
var person = new Person("Test");
throw new Exception("Es wurde ein Fehler geworfen von Mir!");
return person;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment