Randomlogicx
Randomlogicx

Reputation: 231

Spring Mongo reactive Handle Database Error on Save

Can someone please help me as how do i handle database exception when i use Reactive Mongo with Spring webflux ...

I have a Repository class

public interface UserRepository  extends ReactiveMongoRepository<User,String> 
{
   public Mono<User> findByUserName(String userName);
}

Handler method in UserHandler

public Mono<ServerResponse> saveUser(ServerRequest request) {

    Mono<User> user = request.bodyToMono(User.class).map(userObj -> {
        userObj.setPassword(passwordEncoder.encode(userObj.getPassword()));
        return userObj;
    });

    return 
     ServerResponse.ok().body(this.userRepository.insert(user),User.class);
}

I have defined a unique key on username so when the exception throw i want to return a meaningful message to use how can i use OnErrorMap to return a server reponse with message.

I get the below error in console but no error returned to the user

at sun.nio.ch.Invoker$2.run(Invoker.java:218) ~[na:1.8.0_60]
at sun.nio.ch.AsynchronousChannelGroupImpl$1.run(AsynchronousChannelGroupImpl.java:112) ~[na:1.8.0_60]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) ~[na:1.8.0_60]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) ~[na:1.8.0_60]
at java.lang.Thread.run(Thread.java:745) ~[na:1.8.0_60]

Caused by: com.mongodb.MongoWriteException: E11000 duplicate key error collection: letsbuy.users index: username dup key: { : "asoni11" } at com.mongodb.async.client.MongoCollectionImpl$8.onResult(MongoCollectionImpl.java:638) ~[mongodb-driver-async-3.4.3.jar:na] ... 163 common frames omitted

Upvotes: 2

Views: 2644

Answers (1)

Brian Clozel
Brian Clozel

Reputation: 59221

It's a bit counterintuitive, but in that case you need to do something like:

Mono<User> savedUser = request.bodyToMono(User.class).map(userObj -> {
        userObj.setPassword(passwordEncoder.encode(userObj.getPassword()));
        return userObj;
    })
    .flatMap(user -> this.userRepository.insert(user));

    return savedUser
            .flatMap(u -> ServerResponse.ok().syncBody(u))
            .onErrorResume(DuplicateKeyException.class,
                    t -> ServerResponse.status(HttpStatus.BAD_REQUEST).syncBody(t.getMessage()));

Upvotes: 2

Related Questions