From c2d94513d8df1b583958f9218a6cafb2c2c9f8f0 Mon Sep 17 00:00:00 2001 From: Marcos Lopez Gonzalez Date: Fri, 3 May 2019 20:13:38 +0200 Subject: [PATCH] RootCauseFinder improvements --- core-java/pom.xml | 2 +- .../baeldung/exceptions/RootCauseFinder.java | 5 ++++- .../exceptions/RootCauseFinderTest.java | 18 ++++++++++++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/core-java/pom.xml b/core-java/pom.xml index 463b65a4ce..661e787149 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -454,7 +454,7 @@ 2.8.2 - 3.5 + 3.9 2.5 3.6.1 1.0.3 diff --git a/core-java/src/main/java/com/baeldung/exceptions/RootCauseFinder.java b/core-java/src/main/java/com/baeldung/exceptions/RootCauseFinder.java index e05dc7a6cd..064ae27ac1 100644 --- a/core-java/src/main/java/com/baeldung/exceptions/RootCauseFinder.java +++ b/core-java/src/main/java/com/baeldung/exceptions/RootCauseFinder.java @@ -10,10 +10,13 @@ import java.util.Objects; */ public class RootCauseFinder { + private RootCauseFinder() { + } + public static Throwable findCauseUsingPlainJava(Throwable throwable) { Objects.requireNonNull(throwable); Throwable rootCause = throwable; - while (rootCause.getCause() != null) { + while (rootCause.getCause() != null && rootCause.getCause() != rootCause) { rootCause = rootCause.getCause(); } return rootCause; diff --git a/core-java/src/test/java/com/baeldung/exceptions/RootCauseFinderTest.java b/core-java/src/test/java/com/baeldung/exceptions/RootCauseFinderTest.java index cfac81b812..5f61a39ad1 100644 --- a/core-java/src/test/java/com/baeldung/exceptions/RootCauseFinderTest.java +++ b/core-java/src/test/java/com/baeldung/exceptions/RootCauseFinderTest.java @@ -75,6 +75,15 @@ public class RootCauseFinderTest { } } + @Test + public void givenNullDate_whenFindingRootCauseUsingApacheCommons_thenRootCauseNotFound() { + try { + AgeCalculator.calculateAge(null); + } catch (Exception ex) { + assertTrue(ExceptionUtils.getRootCause(ex) instanceof IllegalArgumentException); + } + } + @Test public void givenWrongFormatDate_whenFindingRootCauseUsingGuava_thenRootCauseFound() { try { @@ -93,4 +102,13 @@ public class RootCauseFinderTest { } } + @Test + public void givenNullDate_whenFindingRootCauseUsingGuava_thenRootCauseFound() { + try { + AgeCalculator.calculateAge(null); + } catch (Exception ex) { + assertTrue(Throwables.getRootCause(ex) instanceof IllegalArgumentException); + } + } + }