15 September 2011

.NET - Output an exception including it's inner exceptions

Often when outputting an exception message, you get "see inner exception" or "one or more errors occured" for an aggregate exception. It would be convenient to, when outputting error messages, you get those attached. This extension does that. It keeps going down the inner exceptions until there are no more, and outputs them line by line:

/// <summary>
/// Returns a string that contains the message and inner messages.
/// </summary>
public static string GetFullMessage(this Exception source)
{
    var result = new StringBuilder();
    var ex = source;

    try
    {
        while (ex != null)
        {
            if (result.Length > 0)
                result.Append(Environment.NewLine);

            result.Append(ex.Message);

            //It's handy to get the actual errors when these errors occur.
            if (ex is ReflectionTypeLoadException)
            {
                result.AppendLine("Loader exceptions:");
                var typeErrors = (ex as ReflectionTypeLoadException)?.LoaderExceptions;

                if (typeErrors != null)
                    foreach (var typeError in typeErrors)
                        result.AppendLine(typeError?.Message);
            }
            else if (ex is AggregateException)
            {
                result.AppendLine("Aggregate exceptions:");
                var inner = ex.InnerException;

                while (inner != null)
                {
                    result.AppendLine(inner.Message);
                    inner = inner.InnerException;
                }
            }

            ex = ex.InnerException;
        }
    }
    catch (Exception ex2)
    {
        result.AppendLine("The following error occured in GetFullMessage:");
        result.AppendLine(ex2?.Message);
    }

    return result.ToString();
}

No comments:

Post a Comment