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();
}
///
/// Converts an Exception and its inner exceptions to an AggregateException.
/// Flattens the exception hierarchy into a single AggregateException containing all exceptions.
///
/// The exception to convert
/// An AggregateException containing the original exception and all inner exceptions
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();
FlattenExceptions(exception, exceptions);
return new AggregateException(exceptions);
}
///
/// Recursively flattens exception hierarchy into a list
///
/// Current exception to process
/// List to accumulate flattened exceptions
private static void FlattenExceptions(Exception exception, List 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);
}
}
}
}
}