英文:
How to throw an exception properly when do Flux processing?
问题
已有代码:
private Flux<Integer> testGetFluxTestData() {
return Flux.just(new TestData(1), new TestData(2))
.collectList()
.map(list -> list.stream()
.map(TestData::getId)
.collect(Collectors.toList()))
.flatMapMany(Flux::fromIterable);
}
我想要丰富现有的代码,在接收到某些不允许的数据时抛出异常,我做了以下更改:
private Flux<Integer> testGetFluxTestData2() {
return Flux.just(new TestData(1), new TestData(2))
.collectList()
.flatMapMany(list -> {
if (!list.contains(new TestData(1))) {
return Flux.fromIterable(list.stream()
.map(TestData::getId)
.collect(Collectors.toList()));
} else {
return Flux.error(new IllegalTestDataException("illegal test data 1"));
}
});
}
但是我的实现甚至因为以下这一行而无法编译通过:
Flux.error(new IllegalTestDataException("illegal test data 1"));
请问,您能否建议如何处理我特定情况下的异常抛出?
英文:
Existing code that I have:
private Flux<Integer> testGetFluxTestData() {
return Flux.just(new TestData(1), new TestData(2))
.collectList()
.map(list -> list.stream()
.map(TestData::getId)
.collect(Collectors.toList()))
.flatMapMany(Flux::fromIterable);
}
I want to enrich existing code and throw an exception when some not allowed data received, I made the following changes:
private Flux<Integer> testGetFluxTestData2() {
return Flux.just(new TestData(1), new TestData(2))
.collectList()
.map(list -> {
return !list.contains(new TestData(1)) ?
list.stream()
.map(TestData::getId)
.collect(Collectors.toList()) :
Flux.error(new IllegalTestDataException("illegal test data 1"));
})
.flatMapMany(Flux::fromIterable);
}
but my implementation even noncompilable due to the following line:
Flux.error(new IllegalTestDataException("illegal test data 1"));
Could you please suggest, how to handle exception throwing for my particular scenario?
答案1
得分: 1
你正在尝试从 List<TestData>
进行 map
操作,目标要么是 List<Integer>
,要么是 Flux<?>
(错误),这使得所需的结果类型不明确。在映射函数中返回响应式类型通常是不希望的(你应该在 flatMapping 函数中执行此操作)。
(顺便说一下:即使你在 flatMap
中,也不会起作用,因为在那时,由于 collectList
,你已经在 Mono
API 中,所以 Mono.flatMap
期望将结果返回给 Mono
)。
请注意,map
操作符捕获来自 lambda 的异常并将它们转换为 onError
信号,因此从技术上讲,你可以用 throw
替换 Flux.error
。
否则,你需要将 map
转换为 flatMap
,并将 Flux.error
转换为 Mono.error
,原因如上所述。
英文:
You are attempting to map
from a List<TestData>
to either a List<Integer>
or a Flux<?>
(error), which makes the desired result type ambiguous. Returning a reactive type in a mapping function is generally not desired (you'd want to do that in a flatmapping function).
(side note: even if you were in a flatMap
, it wouldn't work either because at that point you're in Mono
API due to collectList
, so Mono.flatMap
expects a Mono
result to the Function
).
Note that the map
operator catches exceptions from the lambda and turn them into an onError
signal, so technically you could replace the Flux.error
with a throw
.
Otherwise, you'd need to turn the map
into a flatMap
and the Flux.error
into a Mono.error
, for the reasons stated above.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论