Let me start out by saying (for all the test driven devs out there who are going to pick this apart lol) that catching bugs through testing is far better than debugging and catching bugs through error logs. However, that does not mean that test driven development has brought Utopia to earth and that any software that implements proper testing doesn’t have bugs. They still have bugs,,, just a lot fewer bugs.
Scenario
So I’ve been working on a windows service as of late that does a lot of database calls, emails etc. So a lot of external things could happen to cause exceptions and I wanted to be able to quickly look up in a log file to see what errors were occuring. Here’s a quick little class to get an exception and ouput a formatted error message that points to where the problem originates:
class ExceptionFormatter { StringBuilder format = new StringBuilder(); public ExceptionFormatter(Exception exception) { StackTrace stacktrace = new StackTrace(exception, true); var stackframes = stacktrace.GetFrames(); format.Append("********* Error ************\r\n"); format.Append("Message: " + exception.Message + "\r\n"); format.Append("Inner Message: " + (exception.InnerException != null ? exception.InnerException.Message : "") + "\r\n"); foreach (StackFrame frame in stackframes) { if (frame.GetFileLineNumber() != 0 && !string.IsNullOrEmpty(frame.GetFileName())) { format.Append("File Name: " + frame.GetFileName() + "\r\n"); format.Append("Line Number: " + frame.GetFileLineNumber() + "\r\n"); format.Append("Column Number: " + frame.GetFileColumnNumber() + "\r\n"); format.Append("Method Name: " + frame.GetMethod() + "\r\n"); } } format.Append("****************************"); } public override string ToString() { return format.ToString(); } }
This is really simple to use. Just pass the exception into the construct and then call the .ToString() method and you get your formatted error. This iterrates through the stackframe to get the location of the errors on top of what the errors are. Hope this helps!
