如何在 flatMap 中处理异常 – 响应式 Spring

huangapple go评论62阅读模式
英文:

How to handle exception in flatmap - reactive spring

问题

看一下这段代码:

somePostRequest
  .bodyToMono(String.class)
  .flatMap(token -> Mono.just(addTokenToMap(token, bankCode)));

问题在于方法:addTokenToMap() 需要放在 try catch 块中,我想避免这样做。有没有一种方式可以使用 doOnError() 或类似的方法来处理这个问题?

英文:

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?

答案1

得分: 2

如果您创建一个功能性接口和一个辅助方法,那么您的调用站点可以避免使用try-catch。

如果您只需要使用一次,这可能会显得有些多余,但如果您需要经常执行相同的操作,那么它可以节省您一些输入。

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

您的代码变为:

Mono.create(sink(() -> addTokenToMap(token, bankCode)));
英文:

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&lt;T&gt; {
    T get() throws Throwable;
}

public static &lt;T&gt; Consumer&lt;MonoSink&lt;T&gt;&gt; sink(ThrowableSupplier&lt;T&gt; supplier) {
    return sink -&gt; {
        try {
            sink.success(supplier.get());
        }
        catch (Throwable throwable) {
            sink.error(throwable);
        }
    };
}

Your code becomes

Mono.create(sink(() -&gt; addTokenToMap(token, bankCode)));

huangapple
  • 本文由 发表于 2020年8月31日 20:39:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63671014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定