Skip to content

Instantly share code, notes, and snippets.

@benbrandt22
Last active February 7, 2024 11:26
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benbrandt22/8676438 to your computer and use it in GitHub Desktop.
Save benbrandt22/8676438 to your computer and use it in GitHub Desktop.
C# Extension method that generates a list of exception messages from the top level down through all inner exceptions
using System;
using System.Collections.Generic;
using System.Linq;
namespace System {
public static partial class ExceptionExtensions {
/// <summary>
/// Returns a list of all the exception messages from the top-level
/// exception down through all the inner exceptions. Useful for making
/// logs and error pages easier to read when dealing with exceptions.
/// Usage: Exception.Messages()
/// </summary>
public static IEnumerable<string> Messages( this Exception ex ) {
// return an empty sequence if the provided exception is null
if (ex == null) { yield break; }
// first return THIS exception's message at the beginning of the list
yield return ex.Message;
// then get all the lower-level exception messages recursively (if any)
IEnumerable<Exception> innerExceptions = Enumerable.Empty<Exception>();
if (ex is AggregateException && (ex as AggregateException).InnerExceptions.Any())
{
innerExceptions = (ex as AggregateException).InnerExceptions;
}
else if (ex.InnerException != null)
{
innerExceptions = new Exception[] { ex.InnerException };
}
foreach (var innerEx in innerExceptions)
{
foreach (string msg in innerEx.Messages())
{
yield return msg;
}
}
}
}
}
@kiquenet
Copy link

kiquenet commented Apr 9, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment