Skip to content

Commit fa8a29b

Browse files
committed
Issue #85 Exception Unwrapping Example
1 parent b6f61bb commit fa8a29b

2 files changed

Lines changed: 57 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
2+
3+
package de.bytefish.pgbulkinsert.util;
4+
5+
import org.checkerframework.checker.nullness.qual.Nullable;
6+
7+
public class ExceptionUtils {
8+
9+
private ExceptionUtils() {}
10+
11+
@Nullable
12+
public static Throwable getRootCause(@Nullable Throwable t) {
13+
if (t == null) {
14+
return null;
15+
}
16+
17+
Throwable rootCause = null;
18+
Throwable cause = t.getCause();
19+
20+
// Now get to the Inner-Most Cause:
21+
while (cause != null && cause != rootCause) {
22+
rootCause = cause;
23+
cause = cause.getCause();
24+
}
25+
26+
return rootCause;
27+
}
28+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
2+
3+
package de.bytefish.pgbulkinsert.test.util;
4+
5+
import de.bytefish.pgbulkinsert.exceptions.BinaryWriteFailedException;
6+
import de.bytefish.pgbulkinsert.util.ExceptionUtils;
7+
import org.junit.Assert;
8+
import org.junit.Test;
9+
10+
import java.io.IOException;
11+
import java.sql.SQLException;
12+
13+
public class ExceptionUtilsTest {
14+
15+
@Test
16+
public void testExceptionUtils() {
17+
18+
// Exception Hierarchy:
19+
SQLException sqlException = new SQLException("My SQLException");
20+
IOException ioException = new IOException("My IOException with a SQLException cause", sqlException);
21+
BinaryWriteFailedException binaryWriteFailedException = new BinaryWriteFailedException(ioException);
22+
23+
// Get the root cause:
24+
Throwable innerMostException = ExceptionUtils.getRootCause(binaryWriteFailedException);
25+
26+
Assert.assertNotNull(innerMostException);
27+
Assert.assertEquals("My SQLException", innerMostException.getMessage());
28+
}
29+
}

0 commit comments

Comments
 (0)