在我的代码中,我使用典型的 try..catch 抛出并捕获了一个异常。异常中的消息是 An error occured while executing the query. Please check the stack trace for more detail.还有一个带有消息 ValidationException was thrown. 的 InnerException 没有其他 InnerException。但是,当我通过 Visual Studio 2015 查看异常时,我可以展开异常,转到 InnerException 并展开它,然后我看到:

InnerException: Nothing
InnerExceptions: Count=1

然后我可以展开 InnerExceptions 分支并查看我假设的 AggregateException,在这种情况下,它显示
(0): {"Error Parsing query"}
Raw View:

然后,我可以展开 (0) 组以查看诸如“详细信息”之类的属性,它提供完整和详细的错误消息以及“错误代码”和许多其他信息。

当我尝试通过 ex.InnerException.InnerExceptions 通过代码引用“InnerExceptions”时,我不能,因为“InnerExceptions”不是“Exception”的成员。

它如何在 Visual Studio IDE 中可见但无法通过代码使用?

我正在编写使用 IppDotNetSdkForQuickBooksApiV3 NuGet 包的代码。我提到这一点是因为我不确定这是否是从 Intuit 的 API 中添加的。我以前从未遇到过 InnerExceptions 组。

需要明确的是:迭代 InnerException 属性不会返回在上面提到的“详细信息”中找到的相同错误。

c# - 如何访问 InnerException 的 InnerExceptions 属性?-LMLPHP

最佳答案

Exception 类没有名为 InnerExceptions 的成员,但它是 AggregateException 的基类。 Visual Studio 的调试器将找出每个对象的类型,因此能够显示它们拥有的每个属性。

但是 Exception 类的 InnerException 成员不是 AggregateException 类型,只是一个泛型异常。也就是说,Visual Studio 无法根据类型确定您的 InnerException 是否实际上是 AggregateException。要解决这个问题,您需要强制转换。

我不太熟悉 vb.net 语法,在 C# 领域它会是这样的:

((AggregateException)ex.InnerException).InnerExceptions

或者您可以尝试像这样安全地转换:
if (ex.InnerException.GetType() == typeof(AggregateException))
{
    var listOfInnerExceptions = ((AggregateException)ex.InnerException).InnerExceptions;
}

据我所知,VB.net 中有一个 DirectCast(obj, type) 方法可用于此目的,但我对此可能是错误的。

关于c# - 如何访问 InnerException 的 InnerExceptions 属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34203058/

10-11 11:58