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
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()
.
LINQPad.Runtime
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.");
}
}
}
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 -->
Source: Stackoverflow.com