【发布时间】:2019-04-25 09:13:42
【问题描述】:
我试图在 Flux 为空时返回 404,类似于此处:WebFlux functional: How to detect an empty Flux and return 404?
我主要担心的是,当您检查通量是否具有元素时,它会发出该值并且您会丢失它。当我尝试在服务器响应上使用 switch if empty 时,它永远不会被调用(我暗中认为这是因为 Mono 不是空的,只有正文是空的)。
我正在做的一些代码(我的 Router 类上有一个过滤器,用于检查 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.")));
^This 从不调用 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 只检查正文的内容?
【问题讨论】:
标签: spring-webflux project-reactor