Below is a recursive function I've written that's responsible for compiling a string consisting of a Exception
's message, and also each of that Exception
's InnerException
messages.
I've tried to condense everything to one line, but am unsure if this is the most efficient way of approaching this problem.
public static string GetExceptionMessages(Exception exception, int msgCount = 1)
{
return exception != null ? string.Format("{0}: {1}\n{2}", msgCount, exception.Message, GetExceptionMessages(exception.InnerException, ++msgCount)) : string.Empty;
}
And here is code showing the above method in action:
public static void Main(string[] args)
{
try
{
Throw1();
}
catch (Exception e)
{
string messages = GetExceptionMessages(e);
Console.WriteLine(messages);
}
Console.ReadLine();
}
public static void Throw1()
{
try
{
Throw2();
}
catch (Exception e)
{
throw new Exception("Throw1", e);
}
}
public static void Throw2()
{
throw new Exception("Throw2");
}
public static string GetExceptionMessages(Exception exception, int msgCount = 1)
{
return exception != null ? string.Format("{0}: {1}\n{2}", msgCount, exception.Message, GetExceptionMessages(exception.InnerException, ++msgCount)) : string.Empty;
}
Exception.ToString()
. It recursively includes all information including the very valuable stack traces. \$\endgroup\$