I am unable to return Flux<T> in ResponseEntity. In my repository I return Flux<Student>. Now I want to handle this response in controller with switchIfEmpty to handle 404 error code using switchIfEmpty. Below is what I tried:
repository
public interface StudentRepository extends R2dbcRepository<Student, Integer>{
Flux<Student> findByFirstName(String firstName);
}
service
public Flux<Student> getStudentByName(String name){
return repo.findByFirstName(name);
}
Controller (this is where I am not able produce response)
@GetMapping(value="student/name/{name}")
public Flux<ResponseEntity<Student>> getStudentByName(@PathVariable(name = "name",required = true)String name) {
Flux<ResponseEntity<Student>> map = service.getStudentByName(name)
.switchIfEmpty(Mono.error(new NoSuchElementException("student not found")))
.map(stu->new ResponseEntity<>(Mono.just(stu),HttpStatus.OK));
return map;
}
As I was getting Only a single ResponseEntity supported I tried with below code:
@GetMapping(value="student/name/{name}")
public Flux<ResponseEntity<Student>> getStudentByName(@PathVariable(name = "name",required = true)String name) {
Flux<ResponseEntity<Student>> flatMap = service.getStudentByName(name)
.switchIfEmpty(Mono.error(new NoSuchElementException("student not found")))
.flatMap(stu->Flux.just(new ResponseEntity<Student>(stu,HttpStatus.OK)));
return flatMap;
}
I am still getting same exception i.e. Only a single ResponseEntity supported
I have handled NoSuchElementException as global exception.
How do I return Flux<Student> wrapped inside ResponseEntity.. or vice versa as ResponseEntity wrapped inside Flux. What approach should I go with to return Flux object.
Flux<ResponseEntity<Student>doesn't really make sense a http response can only have a single status not multiple. You should have aResponseEntity<Flux<Student>>. Next to that what you are returning isn't aFlux<ResponseEntity<Student>>either, looking at your mapping it is more of aFlux<ResponseEntity<Mono<Student>>>. Which is even more illogical.