Video in progress
When a unique constraint is violated, how do you return a clear "this email is taken" message to the user?
The error doesn't appear at save() time but at flush or commit, and Spring wraps it in a DataIntegrityViolationException. I pull Hibernate's ConstraintViolationException out of it and pick the message by constraint name. An up-front existsBy check is useful, but it can't be the only defense because of races.
📖 Answer
A common mistake:
@Transactional
public void register(SignUp cmd) {
try {
users.save(new User(cmd.email()));
} catch (DataIntegrityViolationException e) { // never gets in here
throw new EmailTakenException();
}
}
save() (with a SEQUENCE id) only does persist(), and the INSERT goes out in the flush before commit, which is after the try block. The error is thrown after the method exits, in the transaction proxy.
Options that work:
// 1) catch it outside the transaction boundary
public void register(SignUp cmd) {
try {
registration.create(cmd); // a @Transactional method
} catch (DataIntegrityViolationException e) {
throw mapConstraint(e);
}
}
private RuntimeException mapConstraint(DataIntegrityViolationException e) {
if (e.getCause() instanceof ConstraintViolationException cve
&& "uk_user_email".equals(cve.getConstraintName())) {
return new EmailTakenException();
}
return e;
}
- Inside the transaction you can also get the error right away with
saveAndFlush(), but after that the transaction is rollback-only: you can't continue, you can only exit.
Give constraints explicit names in the migration (constraint uk_user_email unique (email)), otherwise the database picks an automatic name and the mapping becomes brittle.
Checking up front with existsByEmail is good for UX, since in many cases it shows the error early. But if two requests arrive at the same time, both see "empty", so the unique constraint and the mapping above are still needed.
Sign up to mark studied questions and save your progress.