Generate nicer stacktraces when creating a generated adapter fails.

Otherwise we end up with many InvocationTargetExceptions layered in, which makes
it difficult to identify what actually failed.
This commit is contained in:
Jesse Wilson 2018-09-10 20:41:38 -04:00
parent 5bd9632756
commit 76cd590ca3
4 changed files with 14 additions and 8 deletions

View file

@ -15,6 +15,7 @@
*/
package com.squareup.moshi;
import com.squareup.moshi.internal.Util;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.lang.reflect.Constructor;
@ -103,7 +104,7 @@ abstract class ClassFactory<T> {
} catch (IllegalAccessException e) {
throw new AssertionError();
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
throw Util.rethrowCause(e);
} catch (NoSuchMethodException ignored) {
// Not the expected version of Dalvik/libcore!
}

View file

@ -138,10 +138,7 @@ final class ClassJsonAdapter<T> extends JsonAdapter<T> {
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
Throwable targetException = e.getTargetException();
if (targetException instanceof RuntimeException) throw (RuntimeException) targetException;
if (targetException instanceof Error) throw (Error) targetException;
throw new RuntimeException(targetException);
throw Util.rethrowCause(e);
} catch (IllegalAccessException e) {
throw new AssertionError();
}

View file

@ -254,12 +254,11 @@ final class StandardJsonAdapters {
} catch (IllegalAccessException e) {
throw new RuntimeException(
"Failed to access the generated JsonAdapter for " + rawType, e);
} catch (InvocationTargetException e) {
throw new RuntimeException(
"Failed to construct the generated JsonAdapter for " + rawType, e);
} catch (InstantiationException e) {
throw new RuntimeException(
"Failed to instantiate the generated JsonAdapter for " + rawType, e);
} catch (InvocationTargetException e) {
throw Util.rethrowCause(e);
}
}

View file

@ -21,6 +21,7 @@ import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
@ -95,6 +96,14 @@ public final class Util {
|| name.startsWith("scala.");
}
/** Throws the cause of {@code e}, wrapping it if it is checked. */
public static RuntimeException rethrowCause(InvocationTargetException e) {
Throwable cause = e.getTargetException();
if (cause instanceof RuntimeException) throw (RuntimeException) cause;
if (cause instanceof Error) throw (Error) cause;
throw new RuntimeException(cause);
}
/**
* Returns a type that is functionally equal but not necessarily equal according to {@link
* Object#equals(Object) Object.equals()}.