🎯 What you will learn
Without a central handler, Spring returns HTML error pages or raw stack traces that mobile clients can't parse. A single @RestControllerAdvice class intercepts every exception across all controllers and converts it into uniform JSON. By the end of this lesson you will understand:
@RestControllerAdvice— global exception handler for REST APIs- Extending
ResponseEntityExceptionHandlerto override Spring's built-in responses - Overriding
handleMethodArgumentNotValidfor structured 400 bodies ResponseEntitybuilders:ok,created,notFound,noContent,status- Custom domain exceptions mapped to specific HTTP codes
- The exception resolution order in Spring MVC
@RestControllerAdvice + ResponseEntityExceptionHandler is the expected answer at every level above junior.
🌍 Real-world scenario
Without a central handler, Spring returns HTML error pages that mobile clients can't parse. Samuel adds a single @RestControllerAdvice class that converts every exception — validation errors, 404s, 500s — into uniform JSON responses the NairaSwift app can reliably display.
🛡️ Block 1 — @RestControllerAdvice
@RestControllerAdvice = @ControllerAdvice + @ResponseBody. Extending ResponseEntityExceptionHandler gives you override hooks for all of Spring's built-in MVC exceptions — override the ones you care about, and the rest still work.
LinkedHashMap for insertion order: Using LinkedHashMap instead of Map.of() guarantees the JSON keys appear in the order you put them — timestamp first, messages last — which makes error logs much easier to scan.
📡 Block 2 — ResponseEntity patterns
ResponseEntity<T> gives you complete control over the HTTP response: status code, headers, and body — all in one fluent builder chain. These are the patterns you will use in every Spring Boot controller.
🔍 Block 3 — Custom domain exception + handler
Map each domain concept to its own exception class. The handler converts it to the right HTTP code. This keeps your service layer clean — it throws meaningful exceptions, the handler handles the HTTP translation.
Service stays clean: findByIdOrThrow uses Optional.orElseThrow — the service never touches HTTP concepts. The translation from domain exception to HTTP 404 happens entirely in the advice class.
📋 ResponseEntity status reference
| Builder | Status | Use case |
|---|---|---|
ResponseEntity.ok(body) | 200 | Successful GET / PUT with body |
ResponseEntity.status(201).body(b) | 201 | Resource created (POST) |
ResponseEntity.noContent().build() | 204 | Successful DELETE, no body |
ResponseEntity.badRequest().body(b) | 400 | Client error, validation failure |
ResponseEntity.notFound().build() | 404 | Resource not found |
ResponseEntity.status(409).body(b) | 409 | Conflict (duplicate, state mismatch) |
ResponseEntity.status(500).body(b) | 500 | Unhandled server error |
🎤 Interview Q&A
On a controller it only handles exceptions from that controller. On @ControllerAdvice it handles exceptions from all controllers in the application.
Let business/runtime exceptions propagate to the @ControllerAdvice. Catch only when you can meaningfully recover (e.g., retry logic). Catching exceptions just to re-throw is noise.
Write separate @ExceptionHandler methods — one catching your domain exceptions for 404/409, another catching Exception for 500. Each can return a different Map structure or a dedicated ErrorResponse record.
Inject WebRequest or HttpServletRequest into the @ExceptionHandler method. Call request.getDescription(false) or httpRequest.getRequestURI() to get the path.
Spring checks: (1) @ExceptionHandler on the controller itself; (2) @ExceptionHandler on @ControllerAdvice classes (ordered by @Order / Ordered); (3) HandlerExceptionResolver chain (ResponseEntityExceptionHandler, DefaultHandlerExceptionResolver, SimpleMappingExceptionResolver). First match wins.
📝 Quiz — 5 questions
Next: Spring Boot Config and Profiles →
⚠️ Common mistakes
✅ Key takeaways
- @RestControllerAdvice centralises all error handling across every controller
- Extend ResponseEntityExceptionHandler to customise Spring's built-in exception responses
- ResponseEntity.ok/created/notFound/noContent/status() control status + body + headers
- Map domain exceptions (TransferNotFoundException) to specific HTTP codes
- Always log unhandled exceptions — never silently swallow them
From messy errors to clean JSON APIs
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →