【问题标题】:Get Form Name, Method Name and More Details that caused the exception获取导致异常的表单名称、方法名称和更多详细信息
【发布时间】:2014-01-17 05:45:40
【问题描述】:

我正在尝试使用 Program.cs 文件中的以下代码来捕获未处理的异常。

我正在尝试创建一个包含错误的所有必需信息的字符串。这样我就可以识别代码中发生错误的点。

我的问题是有一种方法可以在编译和混淆后从错误对象中获取以下详细信息

  • 发生错误的表单名称

  • 触发错误的代码行号

  • 以及任何其他有用的信息来查明确切的代码行

    private static void OnUnhandledException(Object sender, UnhandledExceptionEventArgs e)
        {        
       string error;
    
              error = e.Exception.Message + "|" + e.Exception.TargetSite;
          }
    
            private static void OnGuiUnhandedException(object sender, System.Threading.ThreadExceptionEventArgs e)
            {
    
    
       string error;
    
              error = e.Exception.Message + "|" + e.Exception.TargetSite;
    
            } 
    

【问题讨论】:

  • 只要您需要此代码正常运行,您不需要 需要混淆。除了为您诊断错误之外,没有人对反编译错误代码感兴趣。这比程序员想象的要普遍得多。因此,只需关闭混淆以获得简单的解决方法:) 联系混淆器供应商以获得支持,他们都有一些方法来获取可用的堆栈跟踪。
  • @HansPassant 是的,您需要权衡封闭代码的感觉以获得更好的错误处理。他们确实提供了一种方法,但它使易受攻击的代码更容易受到攻击

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


【解决方案1】:

简单地说,

(e.ExceptionObject as Exception).ToString();

解决你的目的。

【讨论】:

    【解决方案2】:

    只需使用 > System.Environment.StackTrace

    try
    {
        //Exception
    
        throw new Exception("An error has happened");
    }
    catch (Exception ex)
    {
         //Open the trace
         System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
         //Write out the error information, you could also do this with a string.Format 
         as I will post lower
         Console.WriteLine(trace.GetFrame(0).GetMethod().ReflectedType.FullName);
         Console.WriteLine("Line: " + trace.GetFrame(0).GetFileLineNumber());
         Console.WriteLine("Column: " + trace.GetFrame(0).GetFileColumnNumber());
    }
    

    使用字符串格式

    String.Format("An error has occurred at {0} at line {1}", trace.GetFrame(0).GetMethod().ReflectedType.FullName,  trace.GetFrame(0).GetFileLineNumber());
    

    【讨论】:

    • UnhandledExceptionEventArgs 没有 Stacktrace,这可以吗?
    • 谢谢,但经过混淆处理后得到的都是一些随机字符。但是当不使用堆栈跟踪时,它会返回正确的数据,即:仅异常对象。有没有办法从中获取更多数据?
    【解决方案3】:

    我编写了以下 sn-p 并已将其用于我的所有应用程序。它遍历所有内部异常和包含您需要的大部分信息的那些异常的堆栈跟踪:

    public static string ExceptionTree(Exception ex)
    {
        // find all inner exceptions
        StringBuilder strbException = new StringBuilder();
        do
        {
            strbException.AppendLine("Exception: " + ex.Message);
            strbException.AppendLine("Stack Trace: " + ex.StackTrace);
            strbException.AppendLine();
    
            ex = ex.InnerException;
        }
        while (ex != null);
    
        return strbException.ToString();
    }
    

    【讨论】:

    • UnhandledExceptionEventArgs 没有 Stacktrace
    猜你喜欢
    • 1970-01-01
    • 2016-03-26
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多