Last active
July 27, 2024 00:19
Demonstrating a "TryCatch" Extension method over IEnumerable
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 (TryGetNextItem(enumerator, handler, out var nextItem)) | |
{ | |
yield return nextItem; | |
} | |
static bool TryGetNextItem(IEnumerator<T> enumerator, Action<Exception> handler, out T? nextItem) | |
{ | |
nextItem = default; | |
try | |
{ | |
(var moreItems, nextItem) = (enumerator.MoveNext(), enumerator.Current); | |
return moreItems; | |
} | |
catch (Exception ex) | |
{ | |
handler(ex); | |
throw; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment