Skip to content

Commit

Permalink
Improve error reporting when default JsonMapper fails to initialize (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
yawkat authored Dec 11, 2024
1 parent 298b27d commit 9cddffc
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion json-core/src/main/java/io/micronaut/json/JsonMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import java.util.Objects;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.stream.Stream;

Expand Down Expand Up @@ -352,12 +353,14 @@ default JsonMapper cloneWithViewClass(@NonNull Class<?> viewClass) {
* @since 4.0.0
*/
static @NonNull JsonMapper createDefault() {
AtomicReference<IllegalStateException> ex = new AtomicReference<>();
return ServiceLoader.load(JsonMapperSupplier.class).stream()
.flatMap(p -> {
try {
JsonMapperSupplier supplier = p.get();
return Stream.ofNullable(supplier);
} catch (Exception e) {
addException(ex, e);
return Stream.empty();
}
})
Expand All @@ -366,10 +369,28 @@ default JsonMapper cloneWithViewClass(@NonNull Class<?> viewClass) {
try {
return Stream.of(jsonMapperSupplier.get());
} catch (Exception e) {
addException(ex, e);
return Stream.empty();
}
})
.findFirst()
.orElseThrow(() -> new IllegalStateException("No JsonMapper implementation found"));
.orElseThrow(() -> {
if (ex.get() != null) {
return ex.get();
} else {
return new IllegalStateException("No default JsonMapper implementation found");
}
});
}

private static void addException(AtomicReference<IllegalStateException> ref, Exception toAdd) {
ref.updateAndGet(existing -> {
if (existing == null) {
return new IllegalStateException("Failed to initialize default JsonMapper", toAdd);
} else {
existing.addSuppressed(toAdd);
return existing;
}
});
}
}

0 comments on commit 9cddffc

Please sign in to comment.