If you want to log or show the information from an Exception object, you might want to include InnerException and StackTrace information. The following ExceptionInformation class will do just that:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; namespace Rvl.Demo { public class ExceptionInformation { private Exception _exception; public Exception Exception { get { return _exception; } set { _exception = value; } } public override string ToString() { string result = string.Empty; StringBuilder informationBuilder = new StringBuilder(string.Empty); while (Exception != null) { informationBuilder.Append(Environment.NewLine); informationBuilder.Append("Message").Append(Environment.NewLine); informationBuilder.AppendFormat("[{0}]", Exception.Message).Append(Environment.NewLine)
informationBuilder.Append(Environment.NewLine);
informationBuilder.Append("StackTrace").Append(Environment.NewLine); informationBuilder.Append("[").Append(Environment.NewLine); informationBuilder.Append(Exception.StackTrace).Append(Environment.NewLine); informationBuilder.Append("]").Append(Environment.NewLine).Append(Environment.NewLine); Exception = Exception.InnerException; } result = informationBuilder.ToString(); return result; } } }
Usage
Exception exception = new Exception(); try { throw new Exception("This is a test exception"); } catch (Exception ex) { exception = ex; } ExceptionInformation information = new ExceptionInformation(); information.Exception = exception; Console.Write(information.ToString());
Result
Message
[This is a test exception]
StackTrace
[
at Rvl.Demo.Test.ExceptionInformationTester.ToStringTest() in C:\Rvl.Demo.Test\ExceptionInformationTester.cs:line 20
]