Nicely format an exception into a string

11,494

You should get all of this by simply calling the .ToString() method of the exception. We use this to log information and you get everything that I believe you are asking for. See MSDN System.Exception.ToString() for more information.

Share:
11,494
russau
Author by

russau

Russ Sayers Twitter: @russaus https://github.com/russau http://tetrisapp.appspot.com/ http://twitterheatmap.com/ http://www.imdb.com/name/nm5363927/

Updated on June 18, 2022

Comments

  • russau
    russau almost 2 years

    I'd like to build a nicely formatted string of a exception for logging. Doing this from silverlight so options like nlog (not there yet), log4net aren't an option.

    Anyone seen the code to build up something like:

    ExceptionType: xxxx
    Message: xxxx
    StackTrace: XXX
    InnerException
        ExceptionType: xxxx
        Message: xxxx
        StackTrace: XXX
    

    I'm presently writing it myself, just hoping there's code out there to do something nicer.

    UPDATE: I was just about to close this q as I came to the same conclusion as Zach, but not going to deprive Zach of the points! :)

    The .ToString() looks like this:

    System.Exception: I can't handle this ---> System.DivideByZeroException: Attempted to divide by zero.
       at MuckingAround.RussTest_Click(Object sender, RoutedEventArgs e)
       --- End of inner exception stack trace ---
       at MuckingAround.RussTest_Click(Object sender, RoutedEventArgs e)
       at System.Windows.Controls.Primitives.ButtonBase.OnClick()
       at System.Windows.Controls.Button.OnClick()
       at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
       at System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
       at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)