Skip to content

Commit 4f8ac23

Browse files
committed
Add ExceptionUnwrapper untility class
1 parent 0a8a3c1 commit 4f8ac23

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,5 +213,5 @@
213213
</build>
214214
</profile>
215215
</profiles>
216-
<version>1.5.1-SNAPSHOT</version>
216+
<version>1.6.0-SNAPSHOT</version>
217217
</project>
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.nordstrom.common.base;
2+
3+
import java.lang.reflect.InvocationTargetException;
4+
import java.util.Arrays;
5+
import java.util.Collections;
6+
import java.util.HashSet;
7+
import java.util.Set;
8+
9+
public class ExceptionUnwrapper {
10+
11+
private static final Set<Class<? extends Exception>> unwrappable =
12+
Collections.unmodifiableSet(new HashSet<>(Arrays.asList(RuntimeException.class, InvocationTargetException.class)));
13+
14+
private ExceptionUnwrapper() {
15+
throw new AssertionError("ExceptionUnwrapper is a static utility class that cannot be instantiated.");
16+
}
17+
18+
/**
19+
* Unwrap the specified exception.<br>
20+
* <br>
21+
* <b>NOTE</b>: This method unwraps the exception chain until it encounters either a non-wrapper exception or an
22+
* exception with no specified cause. The unwrapped exception is returned.
23+
*
24+
* @param throwable exception to be unwrapped
25+
* @return unwrapped exception
26+
*/
27+
public static Throwable unwrap(Throwable throwable) {
28+
return unwrap(throwable, null);
29+
}
30+
31+
/**
32+
* Unwrap the specified exception, optionally retaining wrapper messages.<br>
33+
* <br>
34+
* <b>NOTE</b>: This method unwraps the exception chain until it encounters either a non-wrapper exception or an
35+
* exception with no specified cause. The unwrapped exception is returned.
36+
*
37+
* @param throwable exception to be unwrapped
38+
* @param string builder to compile wrapper messages (may be 'null')
39+
* @return unwrapped exception
40+
*/
41+
public static Throwable unwrap(Throwable throwable, StringBuilder builder) {
42+
Throwable thrown = throwable;
43+
if (thrown != null) {
44+
while (unwrappable.contains(thrown.getClass())) {
45+
Throwable unwrapped = thrown.getCause();
46+
if (unwrapped == null) break;
47+
if (builder != null) builder.append(thrown.getMessage()).append(" -> ");
48+
thrown = unwrapped;
49+
}
50+
}
51+
return thrown;
52+
}
53+
54+
}

0 commit comments

Comments
 (0)