How to combine Flux and ResponseEntity in Spring Webflux controllers

Use switchIfEmpty to throw an exception in case the user doesn't exist:

return repository
    .findById(userId)
    .switchIfEmpty(Mono.error(NotFoundException("User not found")))
    .flatMapIterable{ it.options }
    .map { OptionDto.from(it) }

Then with an exception handler translate it to a 404 response.


You can use by returning Mono with ResponseEntity

like this

public Mono<ResponseEntity<?>> oneRawImage(
        @PathVariable String filename) {
        // tag::try-catch[]
        return imageService.findOneImage(filename)
            .map(resource -> {
                try {
                    return ResponseEntity.ok()
                        .contentLength(resource.contentLength())
                        .body(new InputStreamResource(
                            resource.getInputStream()));
                } catch (IOException e) {
                    return ResponseEntity.badRequest()
                        .body("Couldn't find " + filename +
                            " => " + e.getMessage());
                }
            });         
    }

I have also example like this

  public ResponseEntity<Mono<?>>  newLive(@Valid @RequestBody Life life) {
        Mono<Life> savedLive = liveRepository.save(life);
        if (savedLive != null) {
            return new ResponseEntity<>(savedLive, HttpStatus.CREATED);
        }
        return new ResponseEntity<>(Mono.just(new Life()), HttpStatus.I_AM_A_TEAPOT);
    }

I dislike functional programming in the REST controllers.

Here is an example ReactiveController .