I am trying to return a 404 when a Flux is empty, similar to here:WebFlux functional: How to detect an empty Flux and return 404?
My main concern is that, when you check if the flux has elements it emmits that value and you loose it. And when I try to use switch if empty on the Server Response it is never called (I secretly think it is because the Mono is not empty, only the body is empty).
Some code of what I am doing (I do have a filter on my Router class checking for DataNotFoundException to return a 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 never calls 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."));
}
});
^This looses the emitted element on hasElements.
Is there a way to either recover the emitted element in hasElements or to make the switchIfEmpty only check the contents of the body?