我想在弹簧验证中返回自定义HTTP状态422,而不是默认值400。

我的验证人:

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


我如何在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) {
    ...
}
}


使用此设置,我总是得到400。如何在返回时自定义HTTP状态?

谢谢

最佳答案

验证过程将抛出一个org.springframework.web.bind.MethodArgumentNotValidException,因此您可以向控制器添加异常处理程序:

import org.springframework.web.bind.MethodArgumentNotValidException;

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

    }

09-30 09:35