如何仅从弹簧验证中获取嵌套的异常消息?

How to get only nested exception message form spring validation?

提问人:Andrzej Więcławski 提问时间:8/1/2021 最后编辑:samabcdeAndrzej Więcławski 更新时间:8/23/2021 访问量:236

问:

上下文

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <org.springframework.boot.version>2.1.6.RELEASE</org.springframework.boot.version>
    <mysql-connector-java.version>8.0.15</mysql-connector-java.version>
    <org.apache.tomcat.embed.version>9.0.12</org.apache.tomcat.embed.version>
    <hibernate-validator.version>6.0.13.Final</hibernate-validator.version>
    <javax.el.version>3.0.0</javax.el.version>
    <jstl.version>1.2</jstl.version>
    <java.version>1.8</java.version>
</properties>

我已经准备了类,它扩展并且工作正常 - 它从覆盖的方法抛出。 接下来我准备了 ,它扩展了方法被覆盖的位置,如下所示:BigDecimalEditorPropertyEditorSupportNumberFormatExceptionsetAsText(String text)CustomBindingErrorProcessorDefaultBindingErrorProcessorprocessPropertyAccessException(PropertyAccessException accessException, BindingResult bindingResult)

   public void processPropertyAccessException(PropertyAccessException accessException, 
                                           BindingResult bindingResult) {

    // overwrites NumberFormatException error message
    if(accessException.getCause() instanceof NumberFormatException){

        String fieldName = accessException.getPropertyChangeEvent().getPropertyName();
        String exceptionError = accessException.getCause().getMessage();

        FieldError fieldError = new FieldError(fieldName,
                                               "BINDING_ERROR", 
                                               fieldName + ": " + exceptionError);

        bindingResult.addError(fieldError);
    }else{
        super.processPropertyAccessException(accessException, bindingResult);
    }

} 

它仍然显示(在已验证的表单字段附近)这样一条很长的消息:

无法将 java.lang.String 类型的属性值转换为属性高度所需的类型 java.math.BigDecimal;嵌套异常是 java.lang.NumberFormatException:无法识别的数字!

例如,如果文本包含两个逗号。

问题是 - 如何仅获取嵌套异常的消息“无法识别的数字!

Spring Hibernate 验证 NumberFormatException

评论


答:

1赞 Leonardo Martin 8/19/2021 #1

这里有一个关于它的链接 链接这里

我能够解决它,因为 messages.properties 添加了: typeMismatch.object.camp=出错

评论

0赞 Andrzej Więcławski 8/21/2021
谢谢 - 它有效!文件中只有简单的条目:<projectPath>/src/main/resources/messages.properties “ typeMismatch.weight=Ops!体重出了点问题!typeMismatch.height=Ops!身高出了点问题!typeMismatch.age=操作!年龄出了点问题!“ - 甚至 - ” typeMismatch.java.math.BigDecimal=无法识别数字!! ”现在看起来很简单。难以置信的;)