简体   繁体   English

如何处理平面图中的异常 - 反应式 spring

[英]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.这里的问题是方法: addTokenToMap() - 需要包装在 try catch 块中 - 我希望避免这种情况。 Is there a way to handle this with perhaps doOnError() or something similar?有没有办法用doOnError()或类似的东西来处理这个问题?

If you create a functional interface and a helper method then you can make your call site avoid the try-catch.如果您创建一个功能接口和一个辅助方法,那么您可以让您的呼叫站点避免 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)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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