c# - 从C#WinForms错误消息中提取特定信息

标签 c# winforms error-handling error-logging

我在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())和行号。

最佳答案

实例化一个新的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();


    }
}

关于c# - 从C#WinForms错误消息中提取特定信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61345101/

相关文章:

c# - RoutedUICommand PreviewExecuted Bug?

c# List<myObject> myList.copyTo() 保留引用?

php - 避免在第二个POST请求中在Codeigniter中出现错误403

php - 自定义错误模板引发 fatal error

c# - Asp.net 按钮点击事件和 MVC

c# - 简单注入(inject)器和[导出属性]

c# - Nancy IoC 每个请求自动注册

c# - WinForms 单元测试

c# - 如何设置设计师设置值的顺序?

python - 从调用者的范围引发异常?