Skip to content

Instantly share code, notes, and snippets.

@MoaidHathot
Last active July 27, 2024 00:19
Demonstrating a "TryCatch" Extension method over IEnumerable
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