Spring Boot 04: from JSON to services, validation, and errors
An API can return 400 without reaching your controller breakpoint. JSON conversion or @Valid may reject input before method invocation. This lesson separates receiving a request from accepting it as valid business input.
Version note: this series is based on Spring Boot 3.5.16 because it targets JBoss EAP 8.1. Spring now offers the newer 4.1. For differences between 3.5 and 4.0, see the Spring Boot 4.0 Migration Guide in the sources.
POST /api/tickets
Content-Type: application/json
{"title":"Learn Boot"}
DispatcherServlet → JSON conversion → @Valid
→ Controller → Service → Store
← status + headers + JSONDefine input separately from persistence
// CreateTicket.java
package com.keeponfirst.bootlab;
import jakarta.validation.constraints.NotBlank;
public record CreateTicket(@NotBlank String title) {}CreateTicket is an input DTO with only title. @NotBlank rejects null, empty, and whitespace-only values. HTTP input, business values, and persistence models can differ. Keeping input separate prevents future internal fields from accidentally becoming writable API fields.
@PostMapping("/tickets")
public ResponseEntity<Ticket> create(@Valid @RequestBody CreateTicket request) {
Ticket ticket = service.createBatch(List.of(request.title())).getFirst();
return ResponseEntity.created(URI.create("/api/tickets/" + ticket.id()))
.body(ticket);
}This is a method excerpt; the download contains its imports and class. @RequestBody converts the body to CreateTicket and @Valid requests validation. The controller calls the service and returns 201 with a Location pointing to the new ticket. That contract is explicitly implemented, not a universal consequence of using POST.
Define the error format explicitly
// ApiErrors.java
package com.keeponfirst.bootlab;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ApiErrors {
@ExceptionHandler(MissingTicket.class)
public ResponseEntity<Map<String, String>> missing(MissingTicket error) {
return ResponseEntity.status(404).body(Map.of("code", "TICKET_NOT_FOUND"));
}
@ExceptionHandler(BadTitle.class)
public ResponseEntity<Map<String, String>> badTitle(BadTitle error) {
return ResponseEntity.status(422).body(Map.of("code", "INVALID_TITLE"));
}
@ExceptionHandler({MethodArgumentNotValidException.class,
HttpMessageNotReadableException.class})
public ResponseEntity<Map<String, String>> badRequest(Exception error) {
return ResponseEntity.badRequest().body(Map.of("code", "INVALID_REQUEST"));
}
}This application uses a simple code object. A missing ticket is 404, parsing or field-validation failure is 400, and a rejected title length is 422. These are design choices. Turning all responses into 200 shifts error interpretation onto clients. Spring also supports ProblemDetail, which should be adopted deliberately with client compatibility in mind.
Official table: which exception maps to which status
The Spring Framework 6.2 javadoc for DefaultHandlerExceptionResolver has a mapping table. This resolver turns Spring MVC exceptions into the statuses below.
| Exception | Status | Case in this lab |
|---|---|---|
| HttpMessageNotReadableException | 400 (SC_BAD_REQUEST) | Only an opening brace |
| MethodArgumentNotValidException | 400 (SC_BAD_REQUEST) | Whitespace-only title |
| HandlerMethodValidationException | 400 (SC_BAD_REQUEST) | Does not occur here; see the next section |
| HttpMediaTypeNotSupportedException | 415 (SC_UNSUPPORTED_MEDIA_TYPE) | Not tested |
| HttpRequestMethodNotSupportedException | 405 (SC_METHOD_NOT_ALLOWED) | Not tested |
ApiErrors in this lab catches the first two rows first. The status is still 400, but the body becomes INVALID_REQUEST. The last two rows were not tested and have no custom handler. This is an inference: a non-JSON Content-Type leads to 415, and DELETE on /api/tickets leads to 405. Confirm with real responses.
When the handler misses: one extra @Constraint parameter
The @RequestBody page says that, by default, validation errors cause a MethodArgumentNotValidException, which becomes a 400. If other parameters have @Constraint annotations, method validation applies and HandlerMethodValidationException is raised instead.
// Illustration only; not in the downloadable lab and not executed.
@PostMapping("/tickets")
public ResponseEntity<Ticket> create(
@Valid @RequestBody CreateTicket request,
@RequestHeader("X-Request-Id") @NotBlank String requestId) {
// ...
}@NotBlank above is a Bean Validation constraint annotation. According to the documentation, a blank title now raises HandlerMethodValidationException. ApiErrors does not list it, so the body is not INVALID_REQUEST. By the table in the previous section, the status is still 400. This was not executed; add a test for this case before changing the signature.
ProblemDetail: another error format
The Spring documentation says it supports RFC 9457, Problem Details for HTTP APIs. The status property of ProblemDetail determines the HTTP status. If instance is not set, it is set from the current URL path. Jackson uses application/problem+json as the media type for these responses.
| Item | This lab’s {"code":...} | ProblemDetail |
|---|---|---|
| Format basis | Defined by this lab | RFC 9457 |
| Media type | application/json | application/problem+json |
| What sets the status | ResponseEntity.status(...) | The status property of ProblemDetail |
| Spring MVC’s own exceptions | ApiErrors handles the ones it lists; Spring’s defaults handle the rest | Extend ResponseEntityExceptionHandler and declare it as @ControllerAdvice |
Changing the format changes the API contract. Existing clients read the code field. Before you switch, list the callers that read it.
| Input | Status | Observation |
|---|---|---|
| Valid title | 201 | id, trimmed title, Location |
| Whitespace-only title | 400 | INVALID_REQUEST, no insert |
| Only an opening brace | 400 | INVALID_REQUEST |
| Missing id | 404 | TICKET_NOT_FOUND |
| 81 ASCII characters | 422 | INVALID_TITLE, no insert |
Exercise: change one input property at a time
curl -i -X POST http://127.0.0.1:8080/api/tickets \
-H 'Content-Type: application/json' -d '{"title":" Learn Boot "}'
curl -i -X POST http://127.0.0.1:8080/api/tickets \
-H 'Content-Type: application/json' -d '{"title":" "}'
curl -i -X POST http://127.0.0.1:8080/api/tickets \
-H 'Content-Type: application/json' -d '{'Predict where each stops. The first reaches the service, which trims and stores the title. The second fails Bean Validation; the third fails JSON conversion. Preserve status, headers, and body. Title length uses Java String.length, measured in UTF-16 code units, not universally visible characters.
Check yourself: the limit is 80. What does a title of 81 Chinese characters return? BMP characters such as 工 or 單 count as 1 code unit each, so the length is 81 and the result is 422. An emoji such as U+1F600 takes 2 code units, so 40 of them count as 80, yet the screen shows only 40 characters.
Why can some rejections bypass ApiErrors?
This lab has no Spring Security. The Spring Security documentation says its Servlet support is based on Servlet Filters. In a secured application, a filter can return 401 or 403 before MVC, outside what these controller advice handlers necessarily handle. CORS is not authentication. Adding security requires unauthenticated, forbidden, expired-session, and CSRF cases rather than removing filters to make tests pass.
Answer and migration connection: what changes when CXF becomes MVC?
Even with the same service, parameter conversion, dates, null fields, content types, and error formats may differ between CXF and MVC. Fixed requests are a starting point; compare the response contract that callers depend on. The exercise teaches you to locate the changed layer instead of assigning every HTTP problem to business logic.
Download the complete ticket API lab (ZIP)Next: 05: Database and transaction rollback