4
votes

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?

3

3 Answers

7
votes

You could apply switchIfEmpty operator to your Flux<Location> response.

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

while the posted answers are indeed correct, there is a convenience exception class if you just want to return a status code (plus a reason) and do not want to fiddle with any custom filters or defining your own error response exceptions.

The other benefit is that you do not have to wrap your responses inside of any ResponseEntity Objects, while useful for some cases (for example, created with a location URI), is an overkill for simple status responses.

see also https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/server/ResponseStatusException.html

 return this.locationService.searchLocations(searchFields, pageToken)
        .buffer()
        .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND, "these are not the droids you are lookig for")));
1
votes

What Alexander wrote is correct. You call switchIfEmpty on the Object that is never empty ServerResponse.ok() by definition is not a empty Publisher. I like to handle this cases in revers so invoke the service and then chain all the methods that create the response.

    this.locationService.searchLocations(searchFields, pageToken)
            .buffer()
            .map(t -> ResponseEntity.ok(t))
            .defaultIfEmpty(ResponseEntity.notFound().build());

UPDATE (not sure if it works, but give it a try):

 public Mono<ServerResponse> myRestMethod(ServerRequest serverRequest) {
        return serverRequest.bodyToMono(RequestDTO.class)
                .map((request) -> searchLocations(request.searchFields, request.pageToken))
                .flatMap( t -> ServerResponse
                        .ok()
                        .body(t, ResponseDTO.class)
                )
                .switchIfEmpty(ServerResponse.notFound().build())
                ;
    }