我正在修改一个现有的WinForms应用程序,这是一个自定义的TraceListener设置,记录在应用程序中发生的任何未处理的错误。在我看来,TraceListener似乎获得了异常的消息部分(这是记录的内容),但没有获得其他异常信息。我希望能够获取异常对象(以获取堆栈跟踪和其他信息)。
在我更熟悉的ASP.NET中,我会调用Server.GetLastError来获取最新的异常,但这在WinForms中当然不起作用。
如何获取最新的异常?
发布于 2008-09-18 23:59:29
我假设您已经设置了一个事件处理程序来捕获未处理的域异常和线程异常。在委托中,您可能会调用跟踪侦听器来记录异常。只需发出一个额外的调用来设置异常上下文。
[STAThread]
private static void Main()
{
// Add the event handler for handling UI thread exceptions
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
// Add the event handler for handling non-UI thread exceptions
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
...
Application.Run(new Form1());
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MyTraceListener.Instance.ExceptionContext = e;
Trace.WriteLine(e.ToString());
}
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
// similar to above CurrentDomain_UnhandledException
}
...
Trace.Listeners.Add(MyTraceListener.Instance);
...
class MyTraceListener : System.Diagnostics.TraceListener
{
...
public Object ExceptionContext { get; set; }
public static MyTraceListener Instance { get { ... } }
}在MyTraceListener中的Write方法中,您可以获得异常上下文并使用它。记住同步异常上下文。
https://stackoverflow.com/questions/97104
复制相似问题