Tirion
Tirion

Reputation: 147

How to customize the response of failed validation when using @Valid in SpringBoot

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

Answers (1)

Erfan Ahmed
Erfan Ahmed

Reputation: 1613

  1. First you need to capture the field errors using Errors.
  2. Then check if 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

Related Questions