using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace Flowsharp.Extensions { public static class InvokeExtensions { /// /// Safely invoke methods by catching non fatal exceptions and logging them. /// public static void Invoke(this IEnumerable events, Action dispatch, ILogger logger) { foreach (var sink in events) { try { dispatch(sink); } catch (Exception ex) { HandleException(ex, logger, typeof(T).Name, sink.GetType().FullName); } } } /// /// Safely invoke methods by catching non fatal exceptions and logging them. /// public static async Task InvokeAsync(this IEnumerable events, Func dispatch, ILogger logger) { foreach (var sink in events) { try { await dispatch(sink); } catch (Exception ex) { HandleException(ex, logger, typeof(T).Name, sink.GetType().FullName); } } } private static void HandleException(Exception ex, ILogger logger, string sourceType, string method) { if (ex.IsFatal()) throw ex; logger.LogError(ex, "{Type} thrown from {Method} by {Exception}", sourceType, method, ex.GetType().Name); } } }