简体   繁体   中英

Spring validator custom HTTP status

I'd like to return a custom HTTP status 422 instead of a default 400 on a spring validation.

My validator:

@Component
@RequiredArgsConstructor
public class EmailUpdateDtoValidator implements Validator {
private Errors errors;
private EmailUpdateDto emailUpdateDto;

@Override
public boolean supports(Class<?> clazz) {
    return EmailUpdateDto.class.equals(clazz);
}

@Override
public void validate(Object object, Errors errors) {
    this.errors = errors;
    this.emailUpdateDto = (EmailUpdateDto) object;

    validateEmail();
}

private void validateEmail() {
    if (!Email.isValid(emailUpdateDto.getEmail())) {
        errors.rejectValue("email", UserValidationErrorCodes.EMAIL_NOT_VALID.name());
    }
}
}

How I setup the validation in the Controller:

@Slf4j
@RestController
@RequiredArgsConstructor
public class UserController {
private final EmailUpdateDtoValidator emailUpdateDtoValidator;

@InitBinder("emailUpdateDto")
protected void initEmailValidationBinder(final WebDataBinder binder) {
    binder.addValidators(emailUpdateDtoValidator);
}

@RequestMapping(value = "/users/{hashedId}/email", method = RequestMethod.PUT)
public void updateEmail(@RequestBody @Valid EmailUpdateDto emailUpdateDto) {
    ...
}
}

Using this setup I always get a 400. How could I customize the HTTP status on the return?

Thanks

As workaround you can define a ExceptionHandler and override the default behavior.

 @ControllerAdvice
 public class RestExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseEntity<Object> customHttpStatus() {
        return ResponseEntity.status(422).build();

    }
} 

The validation process would throw an org.springframework.web.bind.MethodArgumentNotValidException , therefore you can add an exception handler to your controller:

import org.springframework.web.bind.MethodArgumentNotValidException;

   @ExceptionHandler
    public ResponseEntity<String> handleException(MethodArgumentNotValidException ex) {
        return new ResponseEntity<String>(HttpStatus.UNPROCESSABLE_ENTITY);

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM