Thymeleaf returning Java Exception message instead of my custom error message. How can I make it return what I want?

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

Thymeleaf returning Java Exception message instead of my custom error message. How can I make it return what I want?

问题

我正在实现表单验证,在 Thymeleaf 的错误消息中对 BigInteger 进行验证时遇到问题。这是我的属性注释:

@Digits(integer = 9, fraction = 0, message="必须是正整数")
private BigInteger myInteger;

控制器部分:

@PostMapping("/")
public String whatever(@Valid @ModelAttribute Entity myEntity, BindingResult result) {
    if (result.hasErrors()) {
        return "index";
    }
    //TODO
    return "index";	
}

最后,HTML 代码部分:

<span th:if="${#fields.hasErrors('myEntity.myInteger')}"
th:errors="*{myEntity.myInteger}"></span>

现在,这对于我的其他 BigDecimal 变量效果良好,但是 BigInteger 导致 Thymeleaf 显示 NumberFormatException 而不是我的自定义消息 "必须是正整数。",可能是因为我不熟悉的一些错误处理优先级的原因。我已经尝试寻找答案,但大多数答案都指向了基于 messages.properties 的解决方案,而我项目文件夹中没有这个文件。我需要做什么才能确保显示我的自定义消息而不是 NumberFormatException

英文:

I am implementing form validation and running into problems with BigInteger validation in thymeleaf's error messages. Here is my property annotation:

@Digits(integer = 9, fraction = 0, message=&quot;Must be a positive integer&quot;)
private BigInteger myInteger;

The Controller:

@PostMapping(&quot;/&quot;)
	public String whatever(@Valid @ModelAttribute Entity myEntity, BindingResult result) {
	
		if (result.hasErrors()) {
			return &quot;index&quot;;
		}
		//TODO
		return &quot;index&quot;;	
}

And finally, the HTML code

&lt;span th:if=&quot;${#fields.hasErrors(&#39;myEntity.myInteger&#39;)}&quot;
th:errors=&quot;*{myEntity.myInteger}&quot;&gt;&lt;/span&gt;

Now, this is working fine for my other BigDecimal variables, but BigInteger causes Thymeleaf to display a NumberFormatException instead of my custom message &quot;Must be a positive integer.&quot;, presumably because of some priority in error-handling that I am unfamiliar with. I have tried looking for answers but most of them direct me to some messages.properties based solution, which is not present in my project folder. What do I need to do to ensure my custom message is displayed instead of the NumberFormatException?

答案1

得分: 1

你可以在 resources 文件夹中创建 messages.properties,然后添加 typeMismatch.table.myInteger = 必须是正整数。其中“table”是你的实体名称,使用小写形式。

英文:

You can just create messages.properties in resources folder and add typeMismatch.table.myInteger = Must be a positive integer . Where "table" is your entity name in lower case.

huangapple
  • 本文由 发表于 2020年10月18日 02:19:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64405838.html
匿名

发表评论

匿名网友

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

确定