Last active
August 29, 2015 14:22
-
-
Save Philo/b43a23ae6f0716f73632 to your computer and use it in GitHub Desktop.
Func's for Logging
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
public class MyObject { | |
public string Message {get;set; } | |
} | |
public class Program { | |
public static void Main() { | |
MyObject myObj = null; | |
Log(myObj.Message); // this will explode in your face with an exception | |
Log(() => return myObj.Message); // this will actually log another message because we caught the exception when the func was invoked | |
Log(() => GetLogMessage(myObj)); | |
} | |
private string GetLogMessage(MyObject obj) { | |
return obj.Message; | |
} | |
public void Log(string logMessage, Exception exception) { | |
} | |
public void Log(string logMessage) { | |
} | |
public void Log(Func<string> logMessage) { | |
try { | |
var resultOfExecutingFunc = logMessage(); // invoke now so I can catch the exception and stop my app breaking | |
Log(resultOfExecutingFunc); | |
} catch(Exception ex) { | |
Log("unable to log message due to exception", ex); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment