有跡象表明,可以有多個的根本原因(例如AggregateException
和ReflectionTypeLoadException
)例外。
我創建了自己class導航樹,然後不同的訪問者吸引到收集全部或僅僅根源。樣本輸出here。下面的相關代碼片段。
public void Accept(ExceptionVisitor visitor)
{
Read(this.exception, visitor);
}
private static void Read(Exception ex, ExceptionVisitor visitor)
{
bool isRoot = ex.InnerException == null;
if (isRoot)
{
visitor.VisitRootCause(ex);
}
visitor.Visit(ex);
visitor.Depth++;
bool isAggregateException = TestComplexExceptionType<AggregateException>(ex, visitor, aggregateException => aggregateException.InnerExceptions);
TestComplexExceptionType<ReflectionTypeLoadException>(ex, visitor, reflectionTypeLoadException => reflectionTypeLoadException.LoaderExceptions);
// aggregate exceptions populate the first element from InnerExceptions, so no need to revisit
if (!isRoot && !isAggregateException)
{
visitor.VisitInnerException(ex.InnerException);
Read(ex.InnerException, visitor);
}
// set the depth back to current context
visitor.Depth--;
}
private static bool TestComplexExceptionType<T>(Exception ex, ExceptionVisitor visitor, Func<T, IEnumerable<Exception>> siblingEnumerator) where T : Exception
{
var complexException = ex as T;
if (complexException == null)
{
return false;
}
visitor.VisitComplexException(ex);
foreach (Exception sibling in siblingEnumerator.Invoke(complexException))
{
visitor.VisitSiblingInnerException(sibling);
Read(sibling, visitor);
}
return true;
}
來源
2015-06-18 19:47:05
kat
可能重複的[查找最內層的異常,而不使用while循環?](http://stackoverflow.com/questions/3876456/find-the-inner-most-exception-without-using- A-while循環) – DavidRR 2015-12-07 18:42:10
如果有的話,它的另外一個重複的,這其中的老年人和有正確答案爲接受。 – 2015-12-08 11:26:38
問題年齡並不總是指定重複的控制標準。例如,考慮另一個問題的數量是這個數字的十倍以上。另外,被接受的答案只反映了提問者的意見。最後,請注意,另一個問題的[最高投票答案](http://stackoverflow.com/a/5792456/1497596)也提供了'GetBaseException()',但是在某些情況下表明瞭它的侷限性。 – DavidRR 2015-12-08 13:15:15