0

There is a Index in db(mongo) if I try to save a data which is already present it throws an DuplicateKeyException but I cannot handle it using try catch.

Model Class

@Document("users")
@Data
public class User {
    @Id
    private ObjectId id;
    @Indexed(unique = true)
    private String username;
    private String password;
}

createUser

@Component
@Slf4j
public class CustomUserDetailsManager implements UserDetailsManager {
    @Autowired
    UserRepository userReposiotry;

    @Override
    public void createUser(UserDetails user) {
        try {
            User newUser = new User();
            newUser.setUsername(user.getUsername());
            newUser.setPassword(user.getPassword());
            userReposiotry.save(newUser);
        } catch (DuplicateKeyException e) {
            log.error("username already exists");
        }
    }
    ...
}

stackTrace

2022-03-23 19:47:37.884 ERROR 10852 --- \[nio-8080-exec-1\] o.a.c.c.C.\[.\[.\[/\].\[dispatcherServlet\]    : Servlet.service() for servlet \[dispatcherServlet\] in context with path \[\] threw exception \[Request processing failed; nested exception is org.springframework.dao.DuplicateKeyException: Write operation error on server localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate key error collection: playground.users index: username dup key: { username: "ahamed" }', details={}}.; nested exception is com.mongodb.MongoWriteException: Write operation error on server localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate key error collection: playground.users index: username dup key: { username: "ahamed" }', details={}}.\] with root cause

I want to handle that error and and send an appropriate response to client.

2
  • Have you imported correct DuplicateKeyException in your CustomUserDetailsManager class? Commented Mar 24, 2022 at 5:51
  • Turns out I imported a wrong DuplicateKeyException. I should have imported this org.springframework.dao.DuplicateKeyException but I imported the other one com.mongodb.DuplicateKeyException . Commented Mar 24, 2022 at 13:50

1 Answer 1

1

I don't know why,But I got it from here

org.springframework.dao.DuplicateKeyException
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.