Concept Flow - Validation error response formatting
Receive HTTP Request
Validate Input Data
Valid
Process
Send Success
End
The server receives a request, checks input data validity, and either processes it or sends back a formatted error response.
public ResponseEntity<?> handleRequest(@Valid @RequestBody User user, BindingResult result) {
if (result.hasErrors()) {
return ResponseEntity.badRequest().body(formatErrors(result));
}
return ResponseEntity.ok("Success");
}| Step | Action | Validation Result | Response Created | Response Sent |
|---|---|---|---|---|
| 1 | Receive HTTP POST with User data | Not checked yet | No | No |
| 2 | Validate User fields (e.g. @NotNull, @Size) | Errors found: name is empty | No | No |
| 3 | Check if result.hasErrors() | True | Yes, formatErrors() creates error list | No |
| 4 | Return ResponseEntity.badRequest() with error body | N/A | Yes | Yes, error response sent |
| 5 | End request processing | N/A | N/A | N/A |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| result.hasErrors() | false | true | true | true |
| errorResponseBody | null | null | [{"field":"name","message":"must not be empty"}] | [{"field":"name","message":"must not be empty"}] |
In Spring Boot, use @Valid and BindingResult to check input validation. If errors exist, use BindingResult.hasErrors() to detect them. Format errors into a clear response body. Return ResponseEntity.badRequest() with error details. Otherwise, proceed with normal processing and return success.