Reputation: 9088
I am trying to find the best approach for default and error handling with reactive.
This is a working code.
public Mono<ServerResponse> retrieveById(ServerRequest request) {
final String id = request.pathVariable("ID");
return context.retrieveUser().flatMap(usr -> {
return repository.findByApptId(Long.parseLong(id), usr.getOrgId()).flatMap(appt -> {
return ServerResponse.ok().contentType(APPLICATION_JSON).bodyValue(appt);
});
});
}
I am trying to add default and error handling.
For default,
return context.retrieveUser().flatMap(usr -> {
return repository.findByApptId(Long.parseLong(apptId), usr.getOrgId()).flatMap(appt -> {
return ServerResponse.ok().contentType(APPLICATION_JSON).bodyValue(appt);
}).defaultIfEmpty(ServerResponse.notFound().build());
The above default add gives error.
The method defaultIfEmpty(ServerResponse) in the type Mono is not applicable for the arguments
(Mono)
Same error with onErrorReturn as well.
Upvotes: 0
Views: 975
Reputation: 14820
Mono#defaultIfEmpty
takes an item T
and returns a Mono<T>
. Which means that if you give it a String
it will return a Mono<String>
.
You are giving it ServerResponse.notFound().build()
which returns a Mono<ServerResponse>
which won’t work since it would give Mono<Mono<ServerResponse>>
.
What you are looking for is Mono#switchIfEmpty
which switches producer (Mono) to another producer if the previous one turned out empty.
Upvotes: 2