C#: Get all inner exceptions messages
Very often InnerException of Exception has some valuable details what happens. Quite often InnerException has an InnerException so more error messages to investigate.
Theoretically there can be unlimited number of Inner Exceptions so below are 2 small snippets to get all messages from them. Both snippets do the same but first in a “while method”, second in recursive way.
/// <summary>
/// Gets all inner exceptions messages.
/// </summary>
/// <param name="ex">The exception</param>
/// <returns>Messages from all inner exceptions.</returns>
public static string GetInnerExceptionMessages(Exception ex)
{
Exception inner = ex.InnerException;
string messages = String.Empty;
while (inner != null)
{
messages += inner.Message;
if (!messages.EndsWith("."))
{
messages += ".";
}
inner = inner.InnerException;
}
return messages;
}
And another method as recursive function from:
http://stackoverflow.com
public string GetInnerException(Exception ex)
{
if (ex.InnerException != null)
{
return string.Format("{0} > {1} ", ex.InnerException.Message,GetInnerException(ex.InnerException));
}
return string.Empty;
}

(232)

