How can I loop through Exception getCause() to find root cause with detail message [duplicate]

The Apache ExceptionUtils provide the following method:

Throwable getRootCause(Throwable throwable) 

as well as

String getRootCauseMessage(Throwable th) 

I normally use the implementation below instead of Apache's one.

Besides its complexity, Apache's implementation returns null when no cause is found, which force me to perform an additional check for null.

Normally when looking for an exception's root/cause I already have a non-null exception to start with, which is for all intended proposes is the cause of the failure at hand, if a deeper cause can't be found.

Throwable getCause(Throwable e) {
    Throwable cause = null; 
    Throwable result = e;

    while(null != (cause = result.getCause())  && (result != cause) ) {
        result = cause;
    }
    return result;
}

Using java 8 Stream API, this can be achieved by:

Optional<Throwable> rootCause = Stream.iterate(exception, Throwable::getCause)
                                      .filter(element -> element.getCause() == null)
                                      .findFirst();

Note that this code is not immune to exception cause loops and therefore should be avoided in production.


Are you asking for something like this?

Throwable cause = originalException;
while(cause.getCause() != null && cause.getCause() != cause) {
    cause = cause.getCause();
}

or am I missing something?