title: Return HTTP CODE in custom validator Spring Rest
body: <p>I'm working on an API REST using Spring and I'm trying to create a new custom validator with 2 validations.</p>
  
  <p>For each validator I want to return a different HTTP CODE to the users but I'm stuck on it, I just know that I can return a boolean in the isValid method. </p>
  
  <p>I hope someone could help me or give me a better way to accomplish this thing.</p>
  
  <h3>UserController.java</h3>
  
  <pre><code>@RestController
  @RequestMapping("user")
  public class UserController {
  @PostMapping
  public ResponseEntity&lt;?&gt; addUser(@Valid @RequestBody User 
       user, Errors errors)  {
  
      //Here I don't now How to read just one error from Validator class, I just want to return 1 error using the HTTP CODE
      if (errors.hasErrors()) {
          return new ResponseEntity&lt;&gt;(HttpStatus.NO_CONTENT); //I'm just using a generic but I want to use the returned by Validator which has 2 validations and should return different errors
      }       
      return new ResponseEntity&lt;&gt;(user, HttpStatus.OK);
    }
   } 
  </code></pre>
  
  <h3>User.java</h3>
  
  <pre><code>public class User {
  
      @NotNull
      private final String name;
  
      @NotNull
      @UserConstraint
      private final Integer age;
  
      public User(@JsonProperty("name") String name, @JsonProperty("age") Integer age) {
          this.name = name;
          this.age = age;
      }
  
      public String getName() {
          return name;
      }
  
      public Integer getAge() {
          return age;
      }
  
  }
  </code></pre>
  
  <h3>UserConstraint.java</h3>
  
  <pre><code>@Documented
  @Constraint(validatedBy = UserValidator.class)
  @Target({ElementType.METHOD, ElementType.FIELD})
  @Retention(RetentionPolicy.RUNTIME)
  public @interface UserConstraint {
     String message() default "Invalid age";
     Class&lt;?&gt;[] groups() default {};
     Class&lt;? extends Payload&gt;[] payload() default {};
  }
  </code></pre>
  
  <h3>UserValidator.java</h3>
  
  <pre><code>public class UserValidator implements ConstraintValidator&lt;UserConstraint, Integer&gt;  {
  
          @Override
          public void initialize(UserConstraint constraintAnnotation) {
          }
  
          @Override
          public boolean isValid(Integer age, ConstraintValidatorContext context) {
  
            if(age &gt; 60) {
                //Here I want to return HTTP CODE 402 to the user 
                return false;
            } else if(age &lt; 18) {
                //Here I want to return HTTP CODE 422 to the user 
                return false;
            }
            return true;  
      }
  }
  </code></pre>
  
  <p>As you can see I'm trying to do some validations with the age and I want to return a different HTTP CODE to users.</p>