Issue
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.
Solution
I don't know why,But I got it from here
org.springframework.dao.DuplicateKeyException
Answered By - dujm
Answer Checked By - Candace Johnson (JavaFixing Volunteer)