如何打印异常的完整堆栈跟踪?

例如,在一个地方..。

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

在另一个地方。

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

我打印的堆栈跟踪只从 a 开始到 b, 它不包括来自 WebException 的内部堆栈跟踪。

How can I print all the stacktrace???

177987 次浏览

使用如下函数:

    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));
}

我通常对异常使用 .ToString()方法以文本形式显示完整的异常信息(包括内部堆栈跟踪) :

catch (MyCustomException ex)
{
Debug.WriteLine(ex.ToString());
}

输出样本:

ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes!
at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24
at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14
--- End of inner exception stack trace ---
at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18
at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23
at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13

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. 得到结果:

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

建议使用与 LINQPad 相关的 nuget包,然后可以使用 exceptionInstance.Dump()

enter image description here

对于.NET 核心:

  • 安装 LINQPad.Runtime

对于.NET 框架4等。

  • 安装 LINQPad

示例代码:

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.");
}
}
}

跑步结果: enter image description here

LinqPad nuget 包是打印异常堆栈信息的最棒的工具。 希望对你有所帮助。