Return 404 when a Flux is empty
Asked Answered
P

4

6

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?

Proselyte answered 22/11, 2018 at 16:36 Comment(0)
P
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.")));
Presentable answered 23/11, 2018 at 19:0 Comment(3)
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?Proselyte
You told you had a filter for your exception. This exception propagates from the Flux<Location> response to the ServerResponsePresentable
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.Proselyte
D
6

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")));
Dougdougal answered 6/11, 2019 at 0:39 Comment(0)
M
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())
                ;
    }
Miru answered 25/11, 2018 at 23:3 Comment(4)
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.Proselyte
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.Miru
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.Proselyte
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.Miru
N
1

Flux::switchIfEmpty gives you an alternate Publisher that you need to do something with if the the service gives you an empty flux. Just call Flux::onComplete on it.

@GetMapping("{id}")
public Flux<Object> getObjects(@PathVariable String id, ServerHttpResponse response) {
    return getObjectsService(id).switchIfEmpty(alternate->{
        response.setStatusCode(HttpStatus.NO_CONTENT);
        alternate.onComplete();
    });
}
Noddy answered 12/1 at 15:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.