How to get the entire string of exceptions in the Application.ThreadException event handler?

advertisements

I was just working on fixing up exception handling in a .NET 2.0 app, and I stumbled onto some weird issue with Application.ThreadException.

What I want is to be able to catch all exceptions from events behind GUI elements (e.g. button_Click, etc.). I then want to filter these exceptions on 'fatality', e.g. with some types of Exceptions the application should keep running and with others it should exit.

In another .NET 2.0 app I learned that, by default, only in debug mode the exceptions actually leave an Application.Run or Application.DoEvents call. In release mode this does not happen, and the exceptions have to be 'caught' using the Application.ThreadException event.

Now, however, I noticed that the exception object passed in the ThreadExceptionEventArgs of the Application.ThreadException event is always the innermost exception in the exception chain. For logging/debugging/design purposes I really want the entire chain of exceptions though. It isn't easy to determine what external system failed for example when you just get to handle a SocketException: when it's wrapped as e.g. a NpgsqlException, then at least you know it's a database problem.

So, how to get to the entire chain of exceptions from this event? Is it even possible or do I need to design my excepion handling in another way?

Note that I do -sort of- have a workaround using Application.SetUnhandledExceptionMode, but this is far from ideal because I'd have to roll my own message loop.

EDIT: to prevent more mistakes, the GetBaseException() method does NOT do what I want: it just returns the innermost exception, while the only thing I already have is the innermost exception. I want to get at the outermost exception!


This question is more usefully phrased and answered here:

Why does the inner exception reach the ThreadException handler and not the actual thrown exception?