gpt4 book ai didi

spring-webflux - 当 Flux 为空时返回 404

转载 作者:行者123 更新时间:2023-12-03 18:40:55 25 4
gpt4 key购买 nike

当 Flux 为空时,我试图返回 404,类似于此处:WebFlux functional: How to detect an empty Flux and return 404?

我主要担心的是,当您检查通量是否包含元素时,它会发出该值,而您会丢失它。当我尝试在服务器响应上使用 switch if empty 时,它永远不会被调用(我偷偷认为这是因为 Mono 不是空的,只有主体是空的)。

我正在做的一些代码(我的路由器类上有一个过滤器,检查 DataNotFoundException 以返回 notFound):

Flux<Location> response = this.locationService.searchLocations(searchFields, pageToken);
return ok()
.contentType(APPLICATION_STREAM_JSON)
.body(response, Location.class)
.switchIfEmpty(Mono.error(new DataNotFoundException("The data you seek is not here.")));

^这从不调用 switchIfEmpty
Flux<Location> response = this.locationService.searchLocations(searchFields, pageToken);

return response.hasElements().flatMap(l ->{
if(l){
return ok()
.contentType(APPLICATION_STREAM_JSON)
.body(response, Location.class);
}
else{
return Mono.error(new DataNotFoundException("The data you seek is not here."));
}
});

^这会丢失 hasElements 上的发射元素。

有没有办法在 hasElements 中恢复发出的元素,或者让 switchIfEmpty 只检查主体的内容?

最佳答案

您可以将 switchIfEmpty 运算符应用于您的 Flux<Location> response

Flux<Location> response = this.locationService
.searchLocations(searchFields, pageToken)
.switchIfEmpty(Mono.error(new DataNotFoundException("The data you seek is not here.")));

关于spring-webflux - 当 Flux 为空时返回 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53435140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com