Last active
July 27, 2024 17:29
-
-
Save MoaidHathot/fc703d633b53697804ff2f3b31cfe124 to your computer and use it in GitHub Desktop.
Demonstrating a "TryCatch" Extension method over IEnumerable, this version with more ValueTuples
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
using Dumpify; | |
Enumerable.Range(0, 10) | |
.Where(i => i % 2 == 0) | |
.Select(i => i == 6 ? throw new Exception("Oops") : i) | |
.Select(i => i * 2) | |
.CatchExceptions(ex => ex.Dump()) | |
.Dump(); | |
public static class TryCatchExtensions | |
{ | |
public static IEnumerable<T?> CatchExceptions<T>(this IEnumerable<T> source, Action<Exception> handler) | |
{ | |
var enumerator = source.GetEnumerator(); | |
while(GetNextItem(enumerator, handler) is (true, var nextItem)) | |
{ | |
yield return nextItem; | |
} | |
static (bool itemFound, T? nextItem) GetNextItem(IEnumerator<T> enumerator, Action<Exception> handler) | |
{ | |
try | |
{ | |
return enumerator.MoveNext() ? (true, enumerator.Current) : (false, default); | |
} | |
catch (Exception ex) | |
{ | |
handler(ex); | |
throw; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment