views:

73

answers:

2

I have a unhandled exception handler (an oxymoron if ever there was one) but I'd like to get more information out of it.

At the moment it logs the exception message, stack trace etc. and recursively does the same for any inner exceptions. However often the exception is a derived type of the exception class and therefore I do not know ahead of time what it will look like. So what I would like is some code to use reflection to output all of the primitive fields and properties to a text file as name/value pairs and then do the same for any non-primitive objects in the object graph recursively.

I had a go at doing this myself but quickly realised I'd have to deal with collections etc. and someone must have done this before. Another option might be to use serialisation I suppose.

Has anyone done this before? Any code out there?

A: 

You could use Reflection to output all of the properties of the Exception, however you should be wary with overly complex logging / exception handling code as an exception inside your exception handler will probably leave you with no useful debug information to debug your original exception. In particular, if you are going to recursively output any non-primative objects of that Exception then consider what would happen if you have any circular references.

I generally just use ex.ToString() whenever I want to log everything - it doesn't look pretty and might not contain all of the data in the exception (unless base classes have overloaded the ToString() method) however I find generally speaking it contains enough information.

Alternatively if you are dealing with custom exceptions that you have control over then you will probably find serialisation a better solution.

Kragen
I have used reflection to get all the properties and fields and then called ToString on them already, now I need to do this recursively. Also I'm swallowing exceptions in my unhandled exception handlers, pretty much the only time when that's the right thing to do. The reason I want to write this code is because the ex.ToString method wasn't giving me the info I needed. For example if you have an SQLException because if a deadlock the ToString method doesn't give you the table name etc. Obviously I could deal with all the expected exceptions case by case, but what about the unexpected ones?
Christopher Edwards
A: 

I'd take a look at the ELMAH project. It's for ASP.NET, so you won't be able to use it out of the box for a WinForms project, but it might have some ideas that spark something.

Brandon