I have a Spring Boot server that listens on endpoint. I accept @RequestBody
as an object:
class Body {
private String name;
}
I want it to accept requests like:
{
"name": "some_name"
}
However, it also accepts:
{
"name": "some_name",
"dummy key":"dummy key value"
}
In that case I want it to throw error. How can I achieve it?
If you want the controller to return an error when the RequestBody
does not match what you are expecting it is enough to add this to your application.properties
:
spring.jackson.deserialization.fail-on-unknown-properties=true
This will return a default 400 response on malformed requests.
@Valid
annotationAdding the @Valid
annotation to your controller performs constraint validation and it will only fail when, for example, you mark a field as to be of a maximum value of 1
but the request tries to set it to 2
. As per the docs:
Marks a property, method parameter or method return type for validation cascading. Constraints defined on the object and its properties are validated when the property, method parameter or method return type is validated.
But since you are not using any of the tools provided by jakarta.validation
this annotation will have no effect on your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With