-1

I have a use case where I need to log a full stack trace with all the details along with line number whenever any exception happens. I see there are two methods I can use here Exception.ToString() vs Exception.Stacktrace but I am confused which one I should use?

Also, I see a lot of StackOverflow posts and this article where people are talking about either using Ben.Demystifier library or some other way.

catch (Exception ex)
{
    Console.WriteLine(ex.Stacktrace);
    Console.WriteLine(ex.ToString());
    // using Ben.Demystifier library
    Console.WriteLine(ex.ToStringDemystified());
}

I just wanted to understand what is the best and recommended way we can use to log a full stack trace of an exception?

cs98
  • 129
  • 2
  • 10
  • If you don't like ToString. use someone eases library that can tidy it up a bit. "*I just wanted to understand what is the best and recommended way we can use to log full stacktrace of an exception*" there is no recommended way, there is just what is and isnt possible. This is a choose your own adventure and your the person who gets to choose, not us – TheGeneral Aug 26 '20 at 05:00
  • You must be seeing the difference between the outcomes of ex.Stacktrace and ex.ToString(). Which one do you think serves your purpose? – Chetan Aug 26 '20 at 05:01

2 Answers2

1

Of an Exception? Use Exception.StackTrace.

The issue to be aware of, however, is that some stack trace information can be lost if a developer makes the mistake of doing something like this:

try{ /* something errors */ }
catch(Exception ex)
{
    //do stuff
    throw ex;
}

...instead of the appropriate way to rethrow exceptions:

try{ /* something errors */ }
catch(Exception ex)
{
    //do stuff
    throw; // <- no "ex"
}

The former will only record the stack trace from the throw point. The latter preserves the stack trace of the original exception.

Colin
  • 4,025
  • 21
  • 40
1

Exception.Stacktrace would give the details about all the methods that have ben executed along with the line numbers. This helps in tracing back the origination of error but it does not provide the error message and other details.

Exception.ToString would provide current exception, the message, the result of calling ToString on the inner exception, and the result of calling Environment.StackTrace. So definitely it is more exhaustive and detailed.

Its always helpful to log on entire error details through Exception.ToString() and work accordingly in case of any unhandled exception. And then you can extract the stack trace of it if needed per your requirements. But again you need to understand your requirements to choose between the two.

You can refer to below link for best practices on exception handling:

  1. https://learn.microsoft.com/en-us/dotnet/standard/exceptions/best-practices-for-exceptions
  2. https://stackify.com/csharp-exception-handling-best-practices/