|
| 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