Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exceptions: How can I get the most possible information?

I have an enterprise application that logs exception information whenever one happens to occur. The application is a combination of C#, and C++.net.

I want to get as much information as I can at the time of the exception. As of right now, we only print out the Message and the stack trace (which gives line numbers in debug builds, but not release).

The goal of any error log is to point out the error to the best of its ability (as close as it can get). I'm curious how I can take this farther? I want more info.

As a for-instance, I know NullReferenceExceptions and InvalidArguementExceptions contain different amounts of information, but I'm not harnessing anything besides the 'Message' Field.

Is my best bet to use reflection and capture all the public members and print them out? Or perhaps chain TONS of type-checks and casts to print them out cleanly? As a constraint, my logging function needs to just take in an argument of type Exception.

like image 660
greggorob64 Avatar asked Dec 07 '22 09:12

greggorob64


2 Answers

In general, the answer is to log ex.ToString(). In general, the ToString method of an object displays what the object wants you to know. In the case of the base Exception class, this includes the message and stack trace, in addition to the same for any InnerException instances. Particular derived classes of Exception may display more information.

Some exceptions like SqlException also capture additional information (like the stored procedure name and linenumber). In these cases, it it helpful to serialize the entire exception and save that as XML in your logging database. Note that not all exception classes can be serialized, so be prepared to punt on the XML portion.

Also, if all you're doing is logging the exception, then you may want to rethrow the exception so that higher levels can have a chance to handle it. Of course, this does not apply when you are already at the "top level".

like image 181
John Saunders Avatar answered Jan 22 '23 23:01

John Saunders


Give this a try:

try 
{
    //...
}
catch(Exception ex)
{
    Messagebox.Show(ex.ToString());
}

It shows a lot of information, including exception type, message and stack trace of all the exeptions (the InnerException of all the exceptions ordered).

More information in MSDN.

like image 27
SysDragon Avatar answered Jan 22 '23 21:01

SysDragon