elsa-core/src/Flowsharp.Abstractions/Extensions/InvokeExtensions.cs

58 lines
1.7 KiB
C#
Raw Normal View History

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