Skip to content

Instantly share code, notes, and snippets.

@MoaidHathot
Last active July 27, 2024 17:29
Show Gist options
  • Save MoaidHathot/fc703d633b53697804ff2f3b31cfe124 to your computer and use it in GitHub Desktop.
Save MoaidHathot/fc703d633b53697804ff2f3b31cfe124 to your computer and use it in GitHub Desktop.
Demonstrating a "TryCatch" Extension method over IEnumerable, this version with more ValueTuples
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