5

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?

Brian Clozel
  • 56,583
  • 15
  • 167
  • 176
Random
  • 1,105
  • 5
  • 24
  • 37

3 Answers3

10

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.")));
Alexander Pankin
  • 3,787
  • 1
  • 13
  • 23
  • But when I do this, how do I know which status code to return? The response object could be a 200 or a 404. Am I missing something? – Random Nov 26 '18 at 09:28
  • 1
    You told you had a filter for your exception. This exception propagates from the Flux response to the ServerResponse – Alexander Pankin Nov 26 '18 at 12:18
  • You are right! My code was returning 500 and a weird error message, I debugged the problem and found that it was that the DefaultExceptionHandler was being called, instead of the filters. "Just" had to add a global error handler with my version of ErrorAttributes to be consistent witht he rest of the app. – Random Nov 26 '18 at 13:16
5

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")));
enolive
  • 151
  • 1
  • 3
1

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())
                ;
    }
piotr szybicki
  • 1,532
  • 1
  • 11
  • 12
  • Will buffer() not make a list of all elements and then return them all in one go? I will prefer if I can emit each element instead of the whole list. – Random Nov 26 '18 at 09:47
  • What does it matter. The response to the client will not be send until the stream, that you return from your rest method, calls onComplete. The fact that you use webflux doesn't mean that client will receive partial response. – piotr szybicki Nov 26 '18 at 10:08
  • Doesn't it? when I curl my response I get the Location objects in a one by one fashion. I expect this will be the case if, for example, a Kafka server calls this. – Random Nov 26 '18 at 11:27
  • sorry I got turn around, you are correct in the original post the response will be return to the client as it comes in. I posted update that I might think achieves what you want. – piotr szybicki Nov 26 '18 at 12:41