ThrowableUtils { public static void setRootCause(Throwable exception, Throwable newRootCause) { Throwable nt = exception; while (nt.getCause() != null) { nt = nt.getCause(); } if (nt == newRootCause) { return; } nt.initCause(newRootCause); }  static Throwable getRootCause(Throwable throwable); static boolean hasCauseType(Throwable throwable, Class<? extends Throwable> causeClass); static boolean hasCauseMessage(Throwable throwable, String message); static void setRootCause(Throwable exception, Throwable newRootCause);  }
@Test public void setRootCauseShouldSetTheCause() { OneException exception = new OneException(new TwoException()); ThrowableUtils.setRootCause(exception, new OtherException()); assertThat(exception).hasCauseInstanceOf(TwoException.class); assertThat(exception).hasRootCauseInstanceOf(OtherException.class); }
@Test public void setRootCauseShouldAvoidSelfCausation() { TwoException cause = new TwoException(); OneException exception = new OneException(cause); ThrowableUtils.setRootCause(exception, cause); assertThat(exception).hasRootCauseInstanceOf(TwoException.class); }