英文:
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<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)));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论