Class CauseUnwrapper
Throwable causes.
Instrumentation frequently needs to unwrap wrapper exceptions (e.g. ExecutionException, framework-specific wrapper types) to find the
underlying error. A naive loop or recursive method that follows Throwable.getCause() (or
a similar library-specific accessor) until some stop condition is met can loop forever, or
overflow the stack if written recursively, when a cause chain contains a cycle - which can happen
with adversarial or buggy exceptions since nothing prevents Throwable.initCause(Throwable) from being used to create one. The helpers in this class detect
such cycles using identity comparisons and stop unwrapping instead of looping.
This class is internal and is hence not for public use. Its APIs are unstable and can change at any time.
-
Method Summary
Modifier and TypeMethodDescriptionstatic ThrowableFollowsThrowable.getCause()to the root cause in the chain, halting safely if the chain contains a cycle.static ThrowableEquivalent tounwrap(Throwable, Predicate, Function), usingThrowable.getCause()to advance to the next cause.static Throwableunwrap(Throwable error, Predicate<Throwable> shouldUnwrap, Function<Throwable, Throwable> nextCause) Repeatedly replaceserrorwithnextCause.apply(error)whileshouldUnwrap.test(error)returnstrue, and returns the last value reached.
-
Method Details
-
unwrap
public static Throwable unwrap(Throwable error, Predicate<Throwable> shouldUnwrap, Function<Throwable, Throwable> nextCause) Repeatedly replaceserrorwithnextCause.apply(error)whileshouldUnwrap.test(error)returnstrue, and returns the last value reached.Unwrapping halts, whichever happens first: when
shouldUnwrapreturnsfalse, whennextCausereturnsnull, or when a throwable that has already been visited (compared by identity) would be visited again. -
unwrap
Equivalent tounwrap(Throwable, Predicate, Function), usingThrowable.getCause()to advance to the next cause. -
rootCause
FollowsThrowable.getCause()to the root cause in the chain, halting safely if the chain contains a cycle.
-