When the @Valid
annotation fails during request validation in a Spring application, Spring automatically returns a 400 Bad Request response by default. The response typically contains a detailed message with the validation errors.
What Happens When @Valid
Fails?
- Request Body Validation:
If @Valid
is applied to a request body (e.g., a @RequestBody
or @ModelAttribute
object), and one or more fields in the request fail the validation constraints (e.g., @NotNull
, @Size
, @Email
), Spring triggers the validation failure.
2. Response:
3. HTTP Status Code: Spring returns an HTTP 400 Bad Request response.
4. Error Body: By default, Spring generates a response body containing validation error details, typically in the form of a JSON or XML structure, depending on the content type requested. This structure includes details about the invalid fields and the specific validation constraints that failed.
Example of Default Validation Error Response
If a request validation fails (for example, due to a missing or invalid field), Spring Boot returns a response similar to this:
{ "timestamp": "2024-08-29T12:34:56.789+00:00", "status": 400, "error": "Bad Request", "message": "Validation failed for object='user'. Error count: 1", "errors": [ { "field": "email", "rejectedValue": "invalid-email", "message": "must be a well-formed email address" } ], "path": "/register" }
Key Components of the Response:
- status:
400
, indicating a Bad Request. - error: Describes the type of error, in this case, "Bad Request."
- message: Provides details about the validation failure.
- errors: Lists the specific fields that failed validation, including the rejected value and the validation error message.
Customizing the Error Response
You can customize how validation errors are handled by creating an exception handler using @ExceptionHandler
for MethodArgumentNotValidException
or by using @ControllerAdvice
to globally handle validation errors. This allows you to structure the error response as desired.
Example of Custom Error Handling:
@RestControllerAdvice public class CustomGlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach(error -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
}
This customization will respond with a more tailored error response for validation failures.
Conclusion:
When the @Valid
annotation fails during request validation in Spring, it responds with an HTTP 400 Bad Request and a detailed message containing the validation errors. You can customize the response if necessary to fit the requirements of your application.