Return 404 when a Flux is empty











up vote
0
down vote

favorite












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?










share|improve this question




























    up vote
    0
    down vote

    favorite












    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?










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      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?










      share|improve this question















      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?







      spring-webflux project-reactor






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 23 at 10:06









      Brian Clozel

      29.5k67198




      29.5k67198










      asked Nov 22 at 16:36









      Random

      60121933




      60121933
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          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.")));





          share|improve this answer





















          • 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 at 9:28










          • You told you had a filter for your exception. This exception propagates from the Flux<Location> response to the ServerResponse
            – Alexander Pankin
            Nov 26 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 at 13:16


















          up vote
          1
          down vote













          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())
          ;
          }





          share|improve this answer























          • 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 at 9: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 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 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 at 12:41











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53435140%2freturn-404-when-a-flux-is-empty%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote



          accepted










          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.")));





          share|improve this answer





















          • 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 at 9:28










          • You told you had a filter for your exception. This exception propagates from the Flux<Location> response to the ServerResponse
            – Alexander Pankin
            Nov 26 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 at 13:16















          up vote
          1
          down vote



          accepted










          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.")));





          share|improve this answer





















          • 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 at 9:28










          • You told you had a filter for your exception. This exception propagates from the Flux<Location> response to the ServerResponse
            – Alexander Pankin
            Nov 26 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 at 13:16













          up vote
          1
          down vote



          accepted







          up vote
          1
          down vote



          accepted






          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.")));





          share|improve this answer












          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.")));






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 23 at 19:00









          Alexander Pankin

          59626




          59626












          • 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 at 9:28










          • You told you had a filter for your exception. This exception propagates from the Flux<Location> response to the ServerResponse
            – Alexander Pankin
            Nov 26 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 at 13:16


















          • 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 at 9:28










          • You told you had a filter for your exception. This exception propagates from the Flux<Location> response to the ServerResponse
            – Alexander Pankin
            Nov 26 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 at 13:16
















          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 at 9:28




          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 at 9:28












          You told you had a filter for your exception. This exception propagates from the Flux<Location> response to the ServerResponse
          – Alexander Pankin
          Nov 26 at 12:18




          You told you had a filter for your exception. This exception propagates from the Flux<Location> response to the ServerResponse
          – Alexander Pankin
          Nov 26 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 at 13:16




          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 at 13:16












          up vote
          1
          down vote













          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())
          ;
          }





          share|improve this answer























          • 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 at 9: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 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 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 at 12:41















          up vote
          1
          down vote













          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())
          ;
          }





          share|improve this answer























          • 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 at 9: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 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 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 at 12:41













          up vote
          1
          down vote










          up vote
          1
          down vote









          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())
          ;
          }





          share|improve this answer














          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())
          ;
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 26 at 12:39

























          answered Nov 25 at 23:03









          piotr szybicki

          423210




          423210












          • 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 at 9: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 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 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 at 12:41


















          • 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 at 9: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 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 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 at 12:41
















          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 at 9:47




          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 at 9: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 at 10:08






          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 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 at 11:27




          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 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 at 12:41




          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 at 12:41


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53435140%2freturn-404-when-a-flux-is-empty%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Trompette piccolo

          Slow SSRS Report in dynamic grouping and multiple parameters

          Simon Yates (cyclisme)