Skip to content

Commit 3d53dc5

Browse files
Rethrow Error from @PostConstruct method instead of wrapping it in RuntimeException
PostConstructAdapterFactory rethrows a RuntimeException cause as-is but wraps everything else. An Error thrown by the @PostConstruct method (AssertionError, OutOfMemoryError, ...) is unchecked like RuntimeException and should propagate as-is, not be smothered in a RuntimeException. Rethrow Error the same way. Adds a regression test.
1 parent 004e7a4 commit 3d53dc5

2 files changed

Lines changed: 23 additions & 0 deletions

File tree

extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ public T read(JsonReader in) throws IOException {
6565
} catch (InvocationTargetException e) {
6666
if (e.getCause() instanceof RuntimeException) {
6767
throw (RuntimeException) e.getCause();
68+
} else if (e.getCause() instanceof Error) {
69+
throw (Error) e.getCause();
6870
}
6971
throw new RuntimeException(e.getCause());
7072
}

extras/src/test/java/com/google/gson/typeadapters/PostConstructAdapterFactoryTest.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,27 @@ public boolean equals(Object o) {
9595
}
9696
}
9797

98+
@Test
99+
public void testErrorFromPostConstructPropagatesAsError() {
100+
Gson gson =
101+
new GsonBuilder().registerTypeAdapterFactory(new PostConstructAdapterFactory()).create();
102+
103+
AssertionError thrown =
104+
assertThrows(
105+
AssertionError.class, () -> gson.fromJson("{\"value\": 1}", ErrorThrowingClass.class));
106+
107+
assertThat(thrown).hasMessageThat().contains("error from post-construct");
108+
}
109+
110+
static class ErrorThrowingClass {
111+
public int value;
112+
113+
@PostConstruct
114+
private void init() {
115+
throw new AssertionError("error from post-construct");
116+
}
117+
}
118+
98119
@SuppressWarnings({"overrides", "EqualsHashCode"}) // for missing hashCode() override
99120
static class MultipleSandwiches {
100121
public List<Sandwich> sandwiches;

0 commit comments

Comments
 (0)