Reputation: 173
Spring is automatically converting Decimal values to Integers while sending data through body of POST Method in REST APIs. While, I want to throw a custom exception if user enters Decimal values. Is there any easy way to do this.
Eg:: If user enters age = 4.3 , then Spring is converting it to 4.
Upvotes: 2
Views: 2997
Reputation: 404
Actually there is a way of preventing user from entering decimal numbers in place of an integer. You can do it this way.
@JsonProperty("age")
@NotNull
@Min(value = 0L, message = "The value must be positive")
@Digits(integer = 10, fraction = 0)
private BigDecimal age;
Basically, you should change the type from int to the BigDecimal, becasue BigDecimal itself supports @Digits annotation, and this way, you can limit the field to only accept 0 decimal points as this example shows. If the user entered decimal value instead of integer, he will recieve 400 Bad Request.
Upvotes: 4
Reputation: 466
if (age instanceof Integer) //dowork();
else //throw custom exception
consider age as type Object and then use the above code to do your testing.
Upvotes: 0