Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return HTTP CODE in custom validator Spring Rest

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.

UserController.java

@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);
  }
 } 

User.java

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;
    }

}

UserConstraint.java

@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 {};
}

UserValidator.java

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.

like image 269
Candres Avatar asked Sep 12 '25 00:09

Candres


1 Answers

You could throw a ResponseStatusException

throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "error message");
like image 92
MevlütÖzdemir Avatar answered Sep 14 '25 14:09

MevlütÖzdemir