| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- using System;
- using System.Collections.Generic;
- namespace Quadarax.Foundation.Core.Exceptions
- {
- public static class ExceptionExc
- {
- public static int GetCode(this Exception e)
- {
- if (!e.Data.Contains("Code"))
- return -1;
- return int.Parse(e.Data["Code"]?.ToString() ?? "-1");
- }
- public static void SetCode(this Exception e, int code)
- {
- e.Data.Add("Code", code);
- }
- public static string Dump(this Exception e)
- {
- var level = 0;
- var sb = new System.Text.StringBuilder();
- sb.Append("[#").Append(level).Append("]:").AppendLine(e.Message);
- var inner = e.InnerException;
- while (inner != null)
- {
- sb.Append("[#").Append(level).Append("]:").AppendLine(inner.Message);
- inner = inner.InnerException;
- }
- if (e.StackTrace != null)
- {
- sb.AppendLine("[#0] Stack list:");
- sb.AppendLine(e.StackTrace);
- }
- return sb.ToString();
- }
- /// <summary>
- /// Converts an Exception and its inner exceptions to an AggregateException.
- /// Flattens the exception hierarchy into a single AggregateException containing all exceptions.
- /// </summary>
- /// <param name="exception">The exception to convert</param>
- /// <returns>An AggregateException containing the original exception and all inner exceptions</returns>
- public static AggregateException ToAggregateException(this Exception exception)
- {
- if (exception == null)
- throw new ArgumentNullException(nameof(exception));
- // If it's already an AggregateException, flatten it to avoid nested AggregateExceptions
- if (exception is AggregateException aggregateException)
- {
- return aggregateException.Flatten();
- }
- var exceptions = new List<Exception>();
- FlattenExceptions(exception, exceptions);
- return new AggregateException(exceptions);
- }
- /// <summary>
- /// Recursively flattens exception hierarchy into a list
- /// </summary>
- /// <param name="exception">Current exception to process</param>
- /// <param name="exceptions">List to accumulate flattened exceptions</param>
- private static void FlattenExceptions(Exception exception, List<Exception> exceptions)
- {
- if (exception == null)
- return;
- // Handle AggregateException specially to avoid deep nesting
- if (exception is AggregateException aggEx)
- {
- foreach (var innerEx in aggEx.InnerExceptions)
- {
- FlattenExceptions(innerEx, exceptions);
- }
- }
- else
- {
- // Add the current exception
- exceptions.Add(exception);
- // Recursively process inner exception
- if (exception.InnerException != null)
- {
- FlattenExceptions(exception.InnerException, exceptions);
- }
- }
- }
- }
- }
|