Is there an annotation that could be used to prevent the following error from getting thrown by my Java application if I send a non numerical value for year in my GET request?
I currently have this:
@NotNull
@Digits(integer = 4, fraction = 0, message = "Provide valid Year in the format YYYY")
@Min(value = 1900, message = "Year must be greater than 1900")
private Integer year;
When I pass a value with letters I get a NumberFormatException before @Digits and @Min is executed. I also tried @Pattern with a regex value but that caused a 500 error.
"Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'yearOfReg'; nested exception is java.lang.NumberFormatException: For input string: \"20c15\"
The answer is very short: no. That's because the validation is configured for the
Integer yearfield. That means that the field must get populated before it can be validated. That population fails if you submit a value that cannot be parsed to anInteger.The best way to handle this case is to add error handling for the mapping exception. For Jackson that's a
MismatchedInputException.An alternative is to change the field to a
String. That allows you to use@Pattern, but you will need to convert yourself. That can be done in the class itself using a getter.