views:

307

answers:

1

I am modifying an existing WinForms app which is setup with a custom TraceListener which logs any unhandled errors that occur in the app. It seems to me like the TraceListener gets the message part of the exception (which is what gets logged), but not the other exception information. I would like to be able to get at the exception object (to get the stacktrace and other info).

In ASP.NET, which I am more familiar with, I would call Server.GetLastError to get the most recent exception, but of course that won't work in WinForms.

How can I get the most recent exception?

+2  A: 

I assume that you have set an event handler that catches unhandled domain exceptions and thread exceptions. In that delegate you probably call the trace listener to log the exception. Simply issue an extra call to set the exception context.

[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 { ... } }
}

On the Write methods in MyTraceListener you can get the exception context and work with that. Remember to sync exception context.

smink