Clean up ExceptionMapper 25/103125/1
authorRobert Varga <robert.varga@pantheon.tech>
Mon, 7 Nov 2022 13:32:08 +0000 (14:32 +0100)
committerRobert Varga <robert.varga@pantheon.tech>
Mon, 7 Nov 2022 13:32:08 +0000 (14:32 +0100)
Use Class.isInstance() and Class.cast() instead of unchecked casts. Also
restructure ExecutionException mapping.

Change-Id: I21b61cd99a715746c865d12b378b1874b925519b
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
common/util/src/main/java/org/opendaylight/yangtools/util/concurrent/ExceptionMapper.java

index 17de23b88c330bb8744d9c53f75a7965964b8056..491148c271af8a9a3739386306d70941f485c21e 100644 (file)
@@ -65,22 +65,23 @@ public abstract class ExceptionMapper<X extends Exception> implements Function<E
     protected abstract X newWithCause(String message, Throwable cause);
 
     @Override
-    @SuppressWarnings("unchecked")
     @SuppressFBWarnings({"BC_UNCONFIRMED_CAST_OF_RETURN_VALUE", "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE"})
     public X apply(final Exception input) {
 
         // If exception is of the specified type,return it.
-        if (exceptionType.isAssignableFrom(input.getClass())) {
-            return (X) input;
+        if (exceptionType.isInstance(input)) {
+            return exceptionType.cast(input);
         }
 
         // If exception is ExecutionException whose cause is of the specified
         // type, return the cause.
-        if (input instanceof ExecutionException && input.getCause() != null) {
-            if (exceptionType.isAssignableFrom(input.getCause().getClass())) {
-                return (X) input.getCause();
+        if (input instanceof ExecutionException) {
+            final var cause = input.getCause();
+            if (exceptionType.isInstance(cause)) {
+                return exceptionType.cast(cause);
+            } else if (cause != null) {
+                return newWithCause(opName + " execution failed", cause);
             }
-            return newWithCause(opName + " execution failed", input.getCause());
         }
 
         // Otherwise return an instance of the specified type with the original