Reputation: 1
See this code:
somePostRequest
.bodyToMono(String.class)
.flatMap(token -> Mono.just(addTokenToMap(token,bankCode)));
Problem here is that the method: addTokenToMap()
- needs to be wrapped in try catch block - which I am looking to avoid. Is there a way to handle this with perhaps doOnError()
or something similar?
Upvotes: 0
Views: 240
Reputation: 44160
If you create a functional interface and a helper method then you can make your call site avoid the try-catch.
It might be overkill if you're only needing to use it once, but if you need to do the same thing a lot then it could save you a bit of typing.
@FunctionalInterface
interface ThrowableSupplier<T> {
T get() throws Throwable;
}
public static <T> Consumer<MonoSink<T>> sink(ThrowableSupplier<T> supplier) {
return sink -> {
try {
sink.success(supplier.get());
}
catch (Throwable throwable) {
sink.error(throwable);
}
};
}
Your code becomes
Mono.create(sink(() -> addTokenToMap(token, bankCode)));
Upvotes: 2