title: Constraints check controller layer vs service layer
body: <p>I'm trying to learn spring and to achieve that i'm building a REST application from scratch. I'm confused where should I check constraints in my application: Controller layer vs. Service layer.
  For example, in create user method I want to check if there is any other user with the same email, since email is unique in my database. I also want to check if password matches(password and "confirm password" fields) etc.</p>
  
  <p>Currently, in my implementation, all this things are verified in Controller layer so I can return a ResponseEntity for every approach.</p>
  
  <pre><code>    @PostMapping("/signUp")
      public ResponseEntity&lt;Object&gt; createUser(@RequestBody RegisterUserDto user) {
  
          if (userService.getUserByEmail(user.getEmailAddress()) != null) {
  
              return ResponseEntity.badRequest().body("email already exists");
          }
  
          if (!user.getPassword().equals(user.getConfirmPassword())) {
  
              return ResponseEntity.badRequest().body("passwords are not the same");
          }
  
          User savedUser = null;
  
          try {
  
              savedUser = userService.createUser(userDtoConversions.convertToEntityRegister(user));
  
          } catch (ParseException e) {
  
              e.printStackTrace();
          }
  
          URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
                  .buildAndExpand(savedUser.getId()).toUri();
  
          return ResponseEntity.created(location).build();
      }
  </code></pre>
  
  <p>Create user method in Service layer:</p>
  
  <pre><code>    @Override
      @Transactional
      public User createUser(User newUser) {
  
          newUser.setDateCreated(new Date());
  
          return userRepository.save(newUser);
      }
  </code></pre>
  
  <p>So which approach is better? If I checks constraints and validations in Service layer, what should I return so I would know in my controller why create user fails?</p>