DotNext by .NET Foundation and Contributors

<PackageReference Include="DotNext" Version="4.15.0" />

 ExceptionAggregator

Represents aggregator of multiple exceptions.
using DotNext.Runtime.CompilerServices; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; namespace DotNext.Runtime.ExceptionServices { [StructLayout(LayoutKind.Auto)] public struct ExceptionAggregator : ISupplier<Exception>, IFunctional<Func<Exception>> { private object exceptionInfo; public bool IsEmpty { [IsReadOnly] get { return exceptionInfo == null; } } [System.Runtime.CompilerServices.NullableContext(1)] public void Add(Exception e) { object obj = exceptionInfo; if (obj != null) { ExceptionDispatchInfo exceptionDispatchInfo = obj as ExceptionDispatchInfo; if (exceptionDispatchInfo == null) (obj as ICollection<Exception>)?.Add(e); else exceptionInfo = <Add>g__CreateList|3_0(exceptionDispatchInfo.SourceException, e); } else exceptionInfo = ExceptionDispatchInfo.Capture(e); } [IsReadOnly] [System.Runtime.CompilerServices.NullableContext(2)] public Exception CreateException() { object obj = exceptionInfo; ExceptionDispatchInfo exceptionDispatchInfo = obj as ExceptionDispatchInfo; if (exceptionDispatchInfo != null) return exceptionDispatchInfo.SourceException; IEnumerable<Exception> enumerable = obj as IEnumerable<Exception>; if (enumerable != null) return new AggregateException(enumerable); return null; } [IsReadOnly] Exception ISupplier<Exception>.Invoke() { return CreateException(); } [IsReadOnly] public void ThrowIfNeeded() { object obj = exceptionInfo; ExceptionDispatchInfo exceptionDispatchInfo = obj as ExceptionDispatchInfo; if (exceptionDispatchInfo == null) { ICollection<Exception> collection = obj as ICollection<Exception>; if (collection != null) { AggregateException ex = new AggregateException(collection); collection.Clear(); throw ex; } } else exceptionDispatchInfo.Throw(); } } }