【问题标题】:Pulling specific information from C# WinForms error messages从 C# WinForms 错误消息中提取特定信息
【发布时间】:2020-08-04 07:00:23
【问题描述】:

我在我的 C# WinForms 项目中设置了一个日志系统,用于写入日志 txt 文件。典型的错误消息如下所示:

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

有什么方法可以获取该错误消息的一部分吗?具体来说,我想提取违规方法(在本例中为DefineControlsLayout())和行号。

【问题讨论】:

  • 这是在调试器中看到的标准异常消息吗?
  • @ChrisBD,我从catch (Exception ex) 收到错误文本,只是将es.ToString() 发送到日志文件。

标签: c# winforms error-handling error-logging


【解决方案1】:

实例化一个新的 StackTrace 并在发生任何异常后记录其中的详细信息。

我使用的原始链接:https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.stacktrace.getframe?view=netframework-4.8

示例代码 using System.Diagnostics;

try
{
    throw new Exception("Fail");
}
catch (Exception e)
{
    StackTrace st = new StackTrace(e);

    // 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();


    }
}

【讨论】:

  • 要获取文件信息,需要使用constructor overload`StackTrace st = new StackTrace(e, true)。
【解决方案2】:

如果你已经捕捉到一个异常类型,那么你有子属性,例如

Exception.StackTrace Exception.TargetSite

我不认为你可以使用它们来拉代码行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-08
    • 2020-10-17
    • 2019-02-22
    • 2018-01-06
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多