Search code examples
c#winformserror-handlingerror-logging

Pulling specific information from C# WinForms error messages


I have a logging system set up in my C# WinForms project that writes to a log txt file. A typical error message looks like this:

Error : 
8:34:48 AM Tuesday, April 21, 2020
  :
  :System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
   at System.Collections.ArrayList.get_Item(Int32 index)
   at System.Windows.Forms.DataGridViewColumnCollection.get_Item(Int32 index)
   at CrossReferenceTool.frmXRefTool.DefineControlsLayout() in <PathToSourceCsFile>:line 306

Is there any way to grab parts of that error message? Specifically, I'd like to pull the offending method (DefineControlsLayout() in this case) and the line number.


Solution

  • Instantiate a new StackTrace and go log the details from that after any exception occurs.

    Original link I used: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stacktrace.getframe?view=netframework-4.8

    Example code using System.Diagnostics;

    try
    {
        throw new Exception("Fail");
    }
    catch (Exception e)
    {
        StackTrace st = new StackTrace(e, true);
    
        // Display the most recent function call.
        StackFrame sf = st.GetFrame(0);
        Console.WriteLine();
        Console.WriteLine("  Exception in method: ");
        Console.WriteLine("      {0}", sf.GetMethod());
    
        if (st.FrameCount > 1)
        {
            // Display the highest-level function call 
            // in the trace.
    
            sf = st.GetFrame(st.FrameCount - 1);
            Console.WriteLine("  Original function call at top of call stack):");
            Console.WriteLine("      {0}", sf.GetMethod());
    
            // will only work if .pdb is included
            var lineNumber = sf.GetFileLineNumber();
            var fileName = sf.GetFileName();
    
    
        }
    }