Accepted answer

You can create and register a 'before create' Application Event listener as detailed in the manual:

public class UserEventHandler {

  private UserRepository repository;

  public void handleUserCreate(User user) {
    //check database

       throw new DuplicateUserException(user);

You can register a @ControllerAdvice to return some meaningful response. For example:

public class ExceptionHandlingAdvice{

    public Map<String, Object>
           handleDuplicateUserException(DuplicateUserException exception){

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("duplicateUser", exception.getUser().getUserName());

        return map;

Related Query

More Query from same tag