score:4

Accepted answer

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

http://docs.spring.io/spring-data/rest/docs/current/reference/html/#events

@RepositoryEventHandler 
public class UserEventHandler {

  @Autowired
  private UserRepository repository;

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

    if(duplicate){
       throw new DuplicateUserException(user);
    }
  }
}

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

@ControllerAdvice
public class ExceptionHandlingAdvice{

    @ExceptionHandler(DuplicateUserException.class)
    @ResponseStatus(HttpStatus.CONFLICT)
    @ResponseBody
    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