我有验证限制:
@Size(min = 3, message = "First name '${validatedValue} must be minimum 3 characters long'")
@Pattern(regexp = "^A(\\w)+$", message = "First name must start with capital letter")
private String firstName;
在 Controller 中,我为请求正文参数添加了 @Valid
注释。
如果验证失败 - Spring 会解决此问题,但我没有收到消息。
为什么会发生这种情况?
我尝试添加此处理程序:
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<String> handle(ConstraintViolationException constraintViolationException) {
Set<ConstraintViolation<?>> violations = constraintViolationException.getConstraintViolations();
String errorMessage = "";
if (!violations.isEmpty()) {
...
} else {
errorMessage = "ConstraintViolationException occured.";
}
return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
}
最佳答案
我想,通过获取字段错误是可能的。
希望下面的示例能够成功
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ResponseBuilder> handleMethodArgumentNotValidException(HttpServletRequest request,
MethodArgumentNotValidException ex) {
BindingResult result = ex.getBindingResult();
List<org.springframework.validation.FieldError> fieldErrors = result.getFieldErrors();
String errorMessage = messageSource.getMessage(ApiResponseCode.ERR_COMMON_REQ_BODY.getCode(),
new Object[] {
fieldErrors.stream().map(field -> field.getDefaultMessage()).collect(Collectors.joining(",")) },
Locale.US);
LOGGER.error(errorMessage, ex);
return new ResponseEntity<ResponseBuilder>(
new ResponseBuilder.Builder(ApiResponseCode.ERR_COMMON_REQ_BODY.getCode(), errorMessage).build(),
HttpStatus.OK);
}
关于java - 如何在 Spring 框架前端接收验证消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60697917/