I'm working on an API REST using Spring and I'm trying to create a new custom validator with 2 validations.
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.
I hope someone could help me or give me a better way to accomplish this thing.
@RestController
@RequestMapping("user")
public class UserController {
@PostMapping
public ResponseEntity<?> 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<>(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<>(user, HttpStatus.OK);
  }
 } 
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;
    }
}
@Documented
@Constraint(validatedBy = UserValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserConstraint {
   String message() default "Invalid age";
   Class<?>[] groups() default {};
   Class<? extends Payload>[] payload() default {};
}
public class UserValidator implements ConstraintValidator<UserConstraint, Integer>  {
        @Override
        public void initialize(UserConstraint constraintAnnotation) {
        }
        @Override
        public boolean isValid(Integer age, ConstraintValidatorContext context) {
          if(age > 60) {
              //Here I want to return HTTP CODE 402 to the user 
              return false;
          } else if(age < 18) {
              //Here I want to return HTTP CODE 422 to the user 
              return false;
          }
          return true;  
    }
}
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.
You could throw a ResponseStatusException 
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "error message");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With