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!
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)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.