1

我正在修改现有的 WinForms 应用程序,该应用程序使用自定义 TraceListener 进行设置,该程序记录应用程序中发生的任何未处理的错误。在我看来, TraceListener 获得了异常的消息部分(这是记录的内容),而不是其他异常信息。我希望能够获取异常对象(获取堆栈跟踪和其他信息)。

在我更熟悉的 ASP.NET 中,我会调用 Server.GetLastError 来获取最新的异常,但当然这在 WinForms 中不起作用。

如何获取最新的异常?

4

1 回答 1

3

我假设您已经设置了一个事件处理程序来捕获未处理的域异常和线程异常。在该委托中,您可能会调用跟踪侦听器来记录异常。只需发出额外的调用来设置异常上下文。

[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 方法上,您可以获得异常上下文并使用它。请记住同步异常上下文。

于 2008-09-18T23:59:29.343 回答