Created
March 4, 2016 20:52
-
-
Save squadwuschel/7d3b954aa96256f6b27e to your computer and use it in GitHub Desktop.
PostSharp - OnExceptionAspect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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