0

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?

GhostCat
  • 137,827
  • 25
  • 176
  • 248

1 Answers1

2

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)));
Michael
  • 41,989
  • 11
  • 82
  • 128