[c#] How to print full stack trace in exception?

For example, in one place...

//---------------a
try
{
    // some network call
}
catch(WebException we)
{
    throw new MyCustomException("some message ....", we);
}

...and in another place...

//--------------b
try
{
    // invoke code above
}
catch(MyCustomException we)
{
    Debug.Writeline(we.stacktrace);   // <----------------
}

The stacktrace I print, it only start from a to b, it doesnt include the inner stacktrace from the WebException.

How can I print all the stacktrace???

This question is related to c# exception-handling stack-trace

The answer is


Use a function like this:

    public static string FlattenException(Exception exception)
    {
        var stringBuilder = new StringBuilder();

        while (exception != null)
        {
            stringBuilder.AppendLine(exception.Message);
            stringBuilder.AppendLine(exception.StackTrace);

            exception = exception.InnerException;
        }

        return stringBuilder.ToString();
    }

Then you can call it like this:

try
{
    // invoke code above
}
catch(MyCustomException we)
{
    Debug.Writeline(FlattenException(we));
}

Recommend to use LINQPad related nuget package, then you can use exceptionInstance.Dump().

enter image description here

For .NET core:

  • Install LINQPad.Runtime

For .NET framework 4 etc.

  • Install LINQPad

Sample code:

using System;
using LINQPad;

namespace csharp_Dump_test
{
    public class Program
    {
        public static void Main()
        {
            try
            {
                dosome();
            }
            catch (Exception ex)
            {
                ex.Dump();
            }
        }

        private static void dosome()
        {
            throw new Exception("Unable.");
        }
    }
}

Running result: enter image description here

LinqPad nuget package is the most awesome tool for printing exception stack information. May it be helpful for you.


1. Create Method: If you pass your exception to the following function, it will give you all methods and details which are reasons of the exception.

public string GetAllFootprints(Exception x)
{
        var st = new StackTrace(x, true);
        var frames = st.GetFrames();
        var traceString = new StringBuilder();

        foreach (var frame in frames)
        {
            if (frame.GetFileLineNumber() < 1)
                continue;

            traceString.Append("File: " + frame.GetFileName());
            traceString.Append(", Method:" + frame.GetMethod().Name);
            traceString.Append(", LineNumber: " + frame.GetFileLineNumber());
            traceString.Append("  -->  ");
        }

        return traceString.ToString();
}

2. Call Method: You can call the method like this.

try
{
    // code part which you want to catch exception on it
}
catch(Exception ex)
{
    Debug.Writeline(GetAllFootprints(ex));
}

3. Get the Result:

File: c:\MyProject\Program.cs, Method:MyFunction, LineNumber: 29  -->  
File: c:\MyProject\Program.cs, Method:Main, LineNumber: 16  --> 

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to exception-handling

Catching FULL exception message Spring Resttemplate exception handling How to get exception message in Python properly Spring Boot REST service exception handling java.net.BindException: Address already in use: JVM_Bind <null>:80 Python FileNotFound The process cannot access the file because it is being used by another process (File is created but contains nothing) Java 8: Lambda-Streams, Filter by Method with Exception Laravel view not found exception How to efficiently use try...catch blocks in PHP

Examples related to stack-trace

Couldn't load memtrack module Logcat Error How to Add Stacktrace or debug Option when Building Android Studio Project How to log as much information as possible for a Java Exception? e.printStackTrace equivalent in python Why is exception.printStackTrace() considered bad practice? How to store printStackTrace into a string Get exception description and stack trace which caused an exception, all as a string How to send a stacktrace to log4j? How to print full stack trace in exception? What is a stack trace, and how can I use it to debug my application errors?