Spring验证器自定义HTTP状态



我想在弹簧验证时返回自定义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());
}
}
}

我如何在控制器中设置验证:

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

作为解决方法,您可以定义ExceptionHandler并覆盖默认行为。

@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity<Object> customHttpStatus() {
return ResponseEntity.status(422).build();
}
} 

相关内容

  • 没有找到相关文章

最新更新