Java · Advanced level

Advanced level · Module 5: REST APIs with Spring Boot · Lesson 3 of 4

Validation and Error Handling

Validate request bodies, return correct status codes and give clients consistent, helpful error responses.

In this lesson you will

  • Validate input with Bean Validation annotations
  • Map exceptions to status codes and error bodies with @ControllerAdvice

Key concepts

@Valid and @NotBlank / @Positive@RequestBodyResponseEntity and status codes@ControllerAdvice

The lesson

Clients send JSON in the request body, which @RequestBody converts to an object. Annotate fields with constraints such as @NotBlank, @Size(max = 100) and @Future, and add @Valid to the parameter; invalid input then produces a 400 response before your code runs.

Return the right status codes: 201 Created with the new resource for POST, 204 No Content for a successful DELETE, 404 when something does not exist and 409 Conflict when a rule such as double booking is broken. ResponseEntity gives full control over the status and headers.

A @ControllerAdvice class turns exceptions into consistent JSON errors in one place, for example mapping EventNotFoundException to 404 with a body containing a message and timestamp. Never return stack traces to clients.

Step by step

  1. Add a POST /events endpoint with @Valid @RequestBody.
  2. Annotate the request record with validation constraints.
  3. Create a not-found exception and map it to 404 in @ControllerAdvice.
  4. Return 201 with the created event.

Practice activity

Add create and cancel endpoints with full validation and a consistent error format for 400, 404 and 409.

Expected result: Each error case returns the documented status and a JSON error body, checked with curl or a REST client.

Check your understanding

  1. What status should a successful POST that creates a resource return?

    Show answer

    201 Created.

  2. What does @ControllerAdvice provide?

    Show answer

    Central handling that converts exceptions into consistent HTTP error responses.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.