joj*_*ojo 92 c# exception-handling stack-trace
例如,在一个地方......
//---------------a
try
{
// some network call
}
catch(WebException we)
{
throw new MyCustomException("some message ....", we);
}
Run Code Online (Sandbox Code Playgroud)
......在另一个地方......
//--------------b
try
{
// invoke code above
}
catch(MyCustomException we)
{
Debug.Writeline(we.stacktrace); // <----------------
}
Run Code Online (Sandbox Code Playgroud)
我打印的堆栈跟踪,它只从a到b开始,它不包含WebException的内部堆栈跟踪.
如何打印所有堆栈跟踪???
Jus*_*tin 166
我通常在异常上使用.ToString()方法在文本中显示完整的异常信息(包括内部堆栈跟踪):
catch (MyCustomException ex)
{
Debug.WriteLine(ex.ToString());
}
Run Code Online (Sandbox Code Playgroud)
样本输出:
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
Run Code Online (Sandbox Code Playgroud)
And*_*are 52
使用这样的函数:
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();
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样调用它:
try
{
// invoke code above
}
catch(MyCustomException we)
{
Debug.Writeline(FlattenException(we));
}
Run Code Online (Sandbox Code Playgroud)
Ogu*_*ALI 14
如果将异常传递给以下函数,它将为您提供所有方法和详细信息,这些都是异常的原因.
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();
}
Run Code Online (Sandbox Code Playgroud)
结果:
文件:c:\ MyProject\Program.cs,方法:MyFunction,LineNumber:29 - >
文件:c:\ MyProject\Program.cs,方法:Main,LineNumber:16 - >
| 归档时间: |
|
| 查看次数: |
123572 次 |
| 最近记录: |