Sub topic 3
Reporting Validation Failures Field by Field
Assume you know Java exceptions, Spring MVC controllers, HTTP status codes, and basic Maven or Gradle usage. A REST API should tell clients which input fields failed without exposing server internals.
When @Valid @RequestBody detects invalid data, Spring MVC raises MethodArgumentNotValidException. A global handler can convert its field errors into a consistent ProblemDetail response:
@RestControllerAdvice
class ApiExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatusCode status,
WebRequest request) {
List<String> errors = ex.getBindingResult().getFieldErrors().stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage())
.toList();
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Validation failed");
problem.setTitle("Invalid request");
problem.setProperty("errors", errors);
return ResponseEntity.status(status).headers(headers).body(problem);
}
}For a blank item, the response can contain:
{
"title": "Invalid request",
"status": 400,
"detail": "Validation failed",
"errors": ["item: must not be blank"]
}Logging Errors Without Noise or Duplication
Log expected client mistakes, such as validation failures, at most briefly or not at all. Log unexpected server failures once, at ERROR level, with the complete exception:
@ExceptionHandler(Exception.class)
ProblemDetail handleUnexpected(Exception ex) {
log.error("Unhandled exception", ex);
return ProblemDetail.forStatusAndDetail(
HttpStatus.INTERNAL_SERVER_ERROR,
"An unexpected error occurred");
}Do not log the same exception in both a controller and the global handler.
Keeping Internal Details Out of Responses
Return field names and safe validation messages, but never stack traces, SQL statements, file paths, or dependency details. Configure Spring Boot defensively:
server.error.include-message=never
server.error.include-binding-errors=never
server.error.include-stacktrace=never
server.error.include-exception=falseA handler should log diagnostic details on the server while returning a stable message to the client.
Testing Error Responses with MockMvc
MockMvc tests Spring MVC without starting a real server:
mockMvc.perform(post("/orders")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"item\":\"\",\"quantity\":1}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors[0]")
.value("item: must not be blank"));Differences in Spring WebFlux
WebFlux uses a reactive request pipeline. Binding failures commonly use WebExchangeBindException, and functional endpoints may use a WebExceptionHandler. @RestControllerAdvice remains useful for annotated controllers, but WebFlux tests use WebTestClient instead of MockMvc.
Exercise
Why should an unexpected exception return a generic message instead of ex.getMessage()?
Show answer
Its message may reveal internal implementation details. Log the full exception on the server and return a safe, stable response to the client.