'Custom message for Type Mismatch validation error while using Spring Boot and Hibernate Validator

Controller

public String dummyAction(@Valid @ModelAttribute DummyInputData inputData) {
        return "success";
    }

Entity

public class DummyInputData {
    private Integer more;

    public Integer getMore() {
        return more;
    }
    
    public DummyInputData setMore(Integer more) {
        this.more = more;
        return this;
    }
}

Once I will send in POST a String in more field like this is my test, I will receive this error:

Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'more'; nested exception is java.lang.NumberFormatException: For input string: \"this is my test\"

I would like to change that message to something custom.

I followed other questions and tutorials. In the end, I tried this kind of overwriting in properties files, though it didn't work. File is properly loaded - I was able to overwrite other messages.

Used declarations in messages properties file

typeMismatch.more=You provided invalid value
javax.validation.constraints.typeMismatch.more=You provided invalid value


javax.validation.constraints.typeMismatch.int={0} Value must be an integer
typeMismatch.int={0} Value must be an integer
javax.validation.constraints.typeMismatch.java.lang.Integer={0} must be an integer
typeMismatch.java.lang.Integer={0} must be an integer
typeMismatch={0} is of invalid format
javax.validation.constraints.typeMismatch={0} is of invalid format

I'm aware that I'm able to use Controller Advice and catch TypeMismatchException, though I would prefer to add a custom message to the validation response. What then would be the proper approach of overwriting that generic type mismatch message?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source