如何在Spring Framework前端接收验证消息?

huangapple go评论87阅读模式
英文:

How to receive validation message on frontend in Spring Framework?

问题

我有验证约束:

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

在控制器中,我对请求体参数使用了@Valid注解。
如果验证失败,Spring会处理此问题,但我没有收到消息
为什么会发生这种情况?

我尝试添加了以下处理程序:

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<String> handle(ConstraintViolationException constraintViolationException) {
        Set<ConstraintViolation<?>> violations = constraintViolationException.getConstraintViolations();
        String errorMessage = "";
        if (!violations.isEmpty()) {
           ...
        } else {
            errorMessage = "ConstraintViolationException occurred.";
        }

        return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
    }
英文:

I have validation constraints:

 @Size(min = 3, message = &quot;First name &#39;${validatedValue} must be minimum 3 characters long&#39;&quot;)
    @Pattern(regexp = &quot;^A(\\w)+$&quot;, message = &quot;First name must start with capital letter&quot;)
    private String firstName;

In controller I have @Valid annotation for the request body argument.
If validation is failed - Spring resolves this, but I do not receive message.
Why does it happen?

I have tried to add this handler:

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity&lt;String&gt; handle(ConstraintViolationException constraintViolationException) {
        Set&lt;ConstraintViolation&lt;?&gt;&gt; violations = constraintViolationException.getConstraintViolations();
        String errorMessage = &quot;&quot;;
        if (!violations.isEmpty()) {
           ...
        } else {
            errorMessage = &quot;ConstraintViolationException occured.&quot;;
        }

        return new ResponseEntity&lt;&gt;(errorMessage, HttpStatus.BAD_REQUEST);
    }

答案1

得分: 0

我猜,通过获取字段错误,可能是可以的。

希望下面的示例能够起作用:

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

I guess, It is possible by getting field error.

Hope below sample works out

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity&lt;ResponseBuilder&gt; handleMethodArgumentNotValidException(HttpServletRequest request,
			MethodArgumentNotValidException ex) {

	BindingResult result = ex.getBindingResult();
	List&lt;org.springframework.validation.FieldError&gt; fieldErrors = result.getFieldErrors();
	String errorMessage = messageSource.getMessage(ApiResponseCode.ERR_COMMON_REQ_BODY.getCode(),
				new Object[] {
						fieldErrors.stream().map(field -&gt; field.getDefaultMessage()).collect(Collectors.joining(&quot;,&quot;)) },
				Locale.US);
	LOGGER.error(errorMessage, ex);
	return new ResponseEntity&lt;ResponseBuilder&gt;(
				new ResponseBuilder.Builder(ApiResponseCode.ERR_COMMON_REQ_BODY.getCode(), errorMessage).build(),
				HttpStatus.OK);
	}

huangapple
  • 本文由 发表于 2020年3月16日 05:39:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/60697917.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定