Para imprimir solo la Messageparte de excepciones profundas, puede hacer algo como esto:
public static string ToFormattedString(this Exception exception)
{
IEnumerable<string> messages = exception
.GetAllExceptions()
.Where(e => !String.IsNullOrWhiteSpace(e.Message))
.Select(e => e.Message.Trim());
string flattened = String.Join(Environment.NewLine, messages); // <-- the separator here
return flattened;
}
public static IEnumerable<Exception> GetAllExceptions(this Exception exception)
{
yield return exception;
if (exception is AggregateException aggrEx)
{
foreach (Exception innerEx in aggrEx.InnerExceptions.SelectMany(e => e.GetAllExceptions()))
{
yield return innerEx;
}
}
else if (exception.InnerException != null)
{
foreach (Exception innerEx in exception.InnerException.GetAllExceptions())
{
yield return innerEx;
}
}
}
Esto atraviesa recursivamente todas las excepciones internas (incluido el caso de AggregateExceptions) para imprimir todas las Messagepropiedades contenidas en ellas, delimitadas por el salto de línea.
P.ej
var outerAggrEx = new AggregateException(
"Outer aggr ex occurred.",
new AggregateException("Inner aggr ex.", new FormatException("Number isn't in correct format.")),
new IOException("Unauthorized file access.", new SecurityException("Not administrator.")));
Console.WriteLine(outerAggrEx.ToFormattedString());
Se produjo aggr externo.
Aggr interno ex.
El número no está en el formato correcto.
Acceso no autorizado a archivos.
No administrador
Necesitará escuchar otras propiedades de Excepción para más detalles. Por ejemplo Datatendrá alguna información. Podrías hacerlo:
foreach (DictionaryEntry kvp in exception.Data)
Para obtener todas las propiedades derivadas (no en la Exceptionclase base ), puede hacer:
exception
.GetType()
.GetProperties()
.Where(p => p.CanRead)
.Where(p => p.GetMethod.GetBaseDefinition().DeclaringType != typeof(Exception));