#region ========================================================================= USING ===================================================================================== using System; using System.Collections.Generic; using System.Linq; using System.Text; #endregion namespace Lumina.Infrastructure.Common.Utilities; /// /// Exception extension methods. /// /// /// Based on https://stackoverflow.com/a/62283895. /// public static class ExceptionUtilities { /// /// Concatenates all inner exception(s) messages of . /// /// The exception for which to get the inner exception(s) message. /// A string representing the concatenated messages of all inner expcetion(s) of . public static string AggregateMessages(this Exception ex) { return ex.GetInnerExceptions().Aggregate(new StringBuilder(), (stringBuilder, exception) => stringBuilder.AppendLine(exception.Message + " -> "), stringBuilder => stringBuilder.ToString()); } /// /// Recursively gets the inner exception(s) of , at depth. /// /// The exception for which to get the inner exception(s). /// The depth of the recursivity of getting the inner exception(s) of . /// A list of exceptions representing the list of inner exception(s) of . public static IEnumerable GetInnerExceptions(this Exception exception, int maximumDepth = 5) { // Check if there are any more inner exceptions to return. if (exception == null || maximumDepth <= 0) yield break; // Yield the current level exception itself. yield return exception; // If the exception is an AggregateException, treat it differently and get its all exceptions. if (exception is AggregateException aggregateException) foreach (Exception? innerException in aggregateException.InnerExceptions.SelectMany(innerException => innerException.GetInnerExceptions(maximumDepth - 1))) yield return innerException; // If it's a normal exception, recursively get its list of inner exceptions and yield them. foreach (Exception innerException in exception.InnerException?.GetInnerExceptions(maximumDepth - 1) ?? []) yield return innerException; } /// /// Concatenates the relevant properties of . /// /// The exception for which to get the relevant properties. /// A string representing the concatenated relevant properties of . public static string AggregateMessage(this Exception ex) { return $"Message: {ex.Message}; CallStack: {ex.StackTrace}"; } }