Reputation: 147
I am using @Valid together with @RequestBody to validate the request body of post call of an API endpoint, for example:
public ResponseEntity<> sendEmail(@Valid @RequestBody EmailPostBody emailPostBody) {
.
.
.
}
When the validation fails, a response as shown below is returned to the caller.
{
"timestamp": "2020-08-04T02:57:22.839+00:00",
"status": 400,
"error": "Bad Request",
"message": "Validation failed for object='emailPostBody'. Error count: 1",
"path": "/email"
}
However, it only says "Validation failed", but doesn't indicate which field is problematic.
I would like to costumize this response to make it more specific, but don't know how.
Could anyone teach me?
Thanks!
Upvotes: 1
Views: 2116
Reputation: 1613
errors
using Errors
.errors.hasErrors()
is true
then you can send your custom error message in ResponseBody
.public ResponseEntity<> sendEmail(@Valid @RequestBody EmailPostBody emailPostBody,
Errors errors) {
if(errors.hasErrors()) {
new ResponseEntity<>(youResponseBodyWithErrorMsg, httpStatusCode)
}
}
Upvotes: 5