简体   繁体   中英

How to handle exception in flatmap - reactive spring

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?

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)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM