-1

How can I easily get all Exception messages, including the InnerExceptions in C#, to output to console or logging for example?

Oliver Moolman
  • 468
  • 5
  • 9
  • 2
    Show what you´ve tried and where you´re stuck. – MakePeaceGreatAgain Jul 25 '18 at 12:52
  • *...to output to console **for logging** for example?* Depending on the logging framework they just accept an exception and they will recursively log its inner exceptions. A bit too broad and basic question imho. – Peter Bons Jul 25 '18 at 12:59
  • The idea of the question was to do some knowledge sharing, because I couldn't find a concise answer when I was looking for it, so hopefully the question should make it easier for people to find a good solution in the future. – Oliver Moolman Jul 25 '18 at 13:02
  • That already exists: https://stackoverflow.com/questions/5928976/what-is-the-proper-way-to-display-the-full-innerexception/5928991#5928991. No need to re-invent that wheel. Could anyone close that as a duplicate please? – MakePeaceGreatAgain Jul 25 '18 at 13:03

2 Answers2

3

The easiest way to do this is to write a recursive function:

For Example:

    public static string ExceptionMessages(Exception ex)
    {
        if (ex.InnerException == null)
        {
            return ex.Message;
        }

        return ex.Message + "  " + ExceptionMessages(ex.InnerException);

    }

This will output all the Messages in a single string.

Oliver Moolman
  • 468
  • 5
  • 9
2

Usually you'd just loop:

catch (Exception ex)
{
    while (ex != null)
    {
        Console.Error.WriteLine(ex.Message);
        ex = ex.InnerException;
    }
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • @Sinatr there's a trade off between detail vs context; when there are lots of inner exceptions (XmlSerializer is a beast for this!), ToString() is simply too voluminous, where-as looking through just the `.Message` output will very quickly tell you the problem. It depends on the context, is what I'm saying. Yes, sometimes `ex.ToString()` will be just fne – Marc Gravell Jul 25 '18 at 14:31