ltome
ltome

Reputation: 29

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

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="Must be a positive integer")
private BigInteger myInteger;

The Controller:

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

And finally, the HTML code

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

Now, this is working fine for my other BigDecimal variables, but BigInteger causes Thymeleaf to display a NumberFormatException instead of my custom message "Must be a positive integer.", 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?

Upvotes: 0

Views: 328

Answers (1)

Seldo97
Seldo97

Reputation: 719

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.

Upvotes: 1

Related Questions