如何获取 System.Exception 的内部 "message" 值?

How can I get the internal "message" value of a System.Exception?

我有一个 FTP 从第三方程序集抛出的非常通用的异常:

Exception of type 'JSchToCSharp.SharpSsh.jsch.SftpException' was thrown.

检查异常时,我看到有一个名为 message(小写 m)的 private/internal 成员,其中包含我的错误消息:

如何获取此消息会员的价值?

我尝试使用反射来获取它,但是从 GetValue:

返回了 null
    BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
        | BindingFlags.Static;
    FieldInfo field = type.GetField(fieldName, bindFlags);
    var value = field.GetValue(instance);

    return value.ToString();

它似乎不是 Non-PublicStatic 所以我有点不确定使用什么作为我的 BindingFlags.

谢谢

从你的断点你可以看到 Exception 不是一般异常,它有一个已知类型,所以你实际上可以捕获该异常类型为:

try {
    ... 
} 
catch(JSchToCSharp.SharpSsh.jsch.SftpException ex1) {
   // I'm sure that ex1.Message will have what you need
}
catch(Exception ex2)
{
  // for any other Exception types...
}

问题似乎是您正在打印 SftpException.Message 而不是 SftpException.message(注意小写 m)。

库的作者认为(出于未知原因)公开一个名为 message 的 public 字段 是个好主意与名为 Message 的 属性 同名,它来自 Exception 基础 class,但包含不同的内容。

这个例子:

void Main()
{
    try
    {
        throw new SftpException(1, "hello");
    }
    catch (SftpException e)
    {
        Console.WriteLine(e.message);
    }
}

产量 "hello".

请注意,您还可以在自定义 SftpException 上使用 ToString 来打印实际的错误消息。这也行得通:

Console.WriteLine(e.ToString());

旁注:

我用ILSpy查看了SftpException class来查看message字段的访问修饰符。它看起来像这样: