有迹象表明,可以有多个的根本原因(例如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