I have below code retuning Mono<Foo>
:
try {
return userRepository.findById(id) // step 1
.flatMap(user -> barRepository.findByUserId( user.getId()) // step 2
.map(bar-> Foo.builder().msg("Already exists").build()) // step 3
.switchIfEmpty(barRepository.save(Bar.builder().userId(user.getId()).build()) // step 4
.map(bar-> Foo.builder().msg("Created").build()) // step 5
))
.doOnError(throwable -> Mono.just(handleError(throwable)));
} catch(Exception e) {
log.error("from catch block");
return Mono.just(handleError(e));
}
If an error occurs in step 1 (e.g. user does not exist by the specified id), will it be caught by doOnError or by try-catch block, or none of these two?
Same question if an error happens in step 2, step 3, step 4.
What is the correct code so that error is always caught by doOnError
and eliminates try-catch?
I am using:
public interface UserRepository extends ReactiveMongoRepository<User, String>
same for barRepository
.
handleError(throwable)
simply does log.error(e.getMessage())
and retuns Foo
.