【问题标题】:How do I access the InnerExceptions property of an InnerException?如何访问 InnerException 的 InnerExceptions 属性?
【发布时间】:2016-03-16 03:46:44
【问题描述】:

在我的代码中,我使用典型的 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# .net vb.net exception intuit


    【解决方案1】:

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

    但是 Exception 类的 InnerException 成员不是 AggregateException 类型,只是一个泛型 Exception。也就是说,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) 方法可用于此目的,但我可能对此有误。

    【讨论】:

    • 感谢您的快速回复。我试过:如果 TypeOf ex.InnerException 是 AggregateException 然后 msg &= "很多错误!" End If If TypeOf ex Is AggregateException Then msg &= "Loss of errors too!" End If Try 'Dim aex As AggregateException = CType(ex.InnerException, AggregateException) Dim aex As AggregateException = DirectCast(ex.InnerException, AggregateException) msg​​ = aex.InnerExceptions.Count Catch ex2 As Exception msg = "仍然不起作用。 :(" 结束尝试,它们似乎都不起作用。
    • 抱歉,我似乎无法让代码格式在 cmets 中工作。如果有帮助,监视窗口会将第一个 InnerException 显示为 System.Exception {Intuit.Ipp.E​​xception.ValidationException} 并将 InnerExceptions 的类型显示为 System.Collections.ObjectModel.ReadOnlyCollection( Intuit.Ipp.E​​xception.IdsError)
    • 啊!我看到您使用的库不是.Net 的一部分...这使事情有些不同:您必须将 InnerException 强制转换为 Intuit.Ipp.E​​xception.ValidationException 而不是 AggregateException (这是一个默认的 .Net 对象,它偶然具有相同类型的成员,我错误地认为你正在处理它......)。关键是你应该告诉 VS 在哪里寻找 InnerExceptions 成员。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多