using System.Linq; namespace System { /// /// Provides extension methods for exceptions. /// [Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public static class ExceptionExtensions { /// /// Returns the message of the inner exception if exists otherwise the message of the exception itself. /// /// The exception. /// The message of the inner exception or the exception itself. public static string GetMessage(this Exception exception) => exception.InnerException?.Message ?? exception.Message; /// /// Returns the message of the exception and its inner exceptions. /// /// The exception. /// The message of the and all its inner exceptions. public static string GetRecursiveMessage(this Exception exception) { if (exception is AggregateException aggregateEx) { return aggregateEx.InnerExceptions .Take(3) .Select(ex => ex.GetRecursiveMessage()) .Aggregate((a, b) => a + " " + b); } if (exception.InnerException != null) { string message = exception.Message; message = message.ReplaceEnd(" See the inner exception for details.", ""); return message + " " + exception.InnerException.GetRecursiveMessage(); } return exception.Message; } } }