Last active
December 21, 2015 09:48
-
-
Save klumsy/6287279 to your computer and use it in GitHub Desktop.
try/catch while retraining strongly typed reference to an anonymous object.
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 static class TryCatch | |
{ | |
public static T Expression<T>(Func<T> lamda, Action<Exception> onException) | |
{ | |
try | |
{ | |
return lamda(); | |
} | |
catch(Exception e) | |
{ | |
onException(e); | |
return default(T); | |
} | |
} | |
} | |
//and example | |
Exception throwexception = null; | |
var results = TryCatch.Expression( | |
//TRY | |
() => | |
{ | |
//simulate exception happening sometimes. | |
if (new Random().Next(3) == 2) | |
{ | |
throw new Exception("test this"); | |
} | |
//return an anonymous object | |
return new { a = 1, b = 2 }; | |
} , | |
//CATCH | |
(e) => { throwexception = e; | |
//retrow if you wish | |
//throw e; | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment