提问人:techno 提问时间:12/30/2013 最后编辑:mehdi lotfitechno 更新时间:8/18/2014 访问量:1534
获取导致异常的表单名称、方法名称和更多详细信息
Get Form Name, Method Name and More Details that caused the exception
问:
我正在尝试使用Program.cs文件中的以下代码来捕获未经处理的异常。
我试图创建一个包含错误所有必需信息的字符串。这样我就可以在代码中识别出发生错误的点。
我的问题是,有没有办法在编译和混淆后从错误对象中获取以下详细信息
发生错误的窗体的名称
触发错误的代码的行号
以及任何其他有用的信息,以查明确切的代码行
private static void OnUnhandledException(Object sender, UnhandledExceptionEventArgs e) { string error; error = e.Exception.Message + "|" + e.Exception.TargetSite; } private static void OnGuiUnhandedException(object sender, System.Threading.ThreadExceptionEventArgs e) { string error; error = e.Exception.Message + "|" + e.Exception.TargetSite; }
答:
0赞
Ted
12/30/2013
#1
我编写了以下代码片段,并已将其用于我的所有应用程序。它会遍历所有内部异常和这些异常的堆栈跟踪,这些异常包含所需的大部分信息:
public static string ExceptionTree(Exception ex)
{
// find all inner exceptions
StringBuilder strbException = new StringBuilder();
do
{
strbException.AppendLine("Exception: " + ex.Message);
strbException.AppendLine("Stack Trace: " + ex.StackTrace);
strbException.AppendLine();
ex = ex.InnerException;
}
while (ex != null);
return strbException.ToString();
}
评论
1赞
techno
12/30/2013
UnhandledExceptionEventArgs 没有 Stacktrace
0赞
Philip Gullick
12/30/2013
#2
只需使用 > System.Environment.StackTrace
try
{
//Exception
throw new Exception("An error has happened");
}
catch (Exception ex)
{
//Open the trace
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
//Write out the error information, you could also do this with a string.Format
as I will post lower
Console.WriteLine(trace.GetFrame(0).GetMethod().ReflectedType.FullName);
Console.WriteLine("Line: " + trace.GetFrame(0).GetFileLineNumber());
Console.WriteLine("Column: " + trace.GetFrame(0).GetFileColumnNumber());
}
使用字符串。格式
String.Format("An error has occurred at {0} at line {1}", trace.GetFrame(0).GetMethod().ReflectedType.FullName, trace.GetFrame(0).GetFileLineNumber());
评论
0赞
techno
12/30/2013
UnhandledExceptionEventArgs 没有 Stacktrace,这行得通吗?
0赞
Philip Gullick
12/30/2013
@techno stackoverflow.com/questions/10202987/......
0赞
techno
12/30/2013
谢谢,但是在混淆之后,得到的只是一些随机字符。但是当没有使用堆栈跟踪时,它会返回正确的数据,即:仅异常对象。有没有办法从中获取更多数据?
0赞
Ankush Madankar
12/30/2013
#3
只是
(e.ExceptionObject as Exception).ToString();
解决你的目标。
评论