🎯 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 ResponseEntityExceptionHandler to override Spring's built-in responses
  • Overriding handleMethodArgumentNotValid for structured 400 bodies
  • ResponseEntity builders: ok, created, notFound, noContent, status
  • Custom domain exceptions mapped to specific HTTP codes
  • The exception resolution order in Spring MVC
💼 Interview reality: "How do you return consistent error JSON across all controllers?" is a standard Spring Boot question. Knowing @RestControllerAdvice + ResponseEntityExceptionHandler is the expected answer at every level above junior.

🌍 Real-world scenario

🌍
NairaSwift (Lagos, Nigeria)
Consistent error JSON for every failure path

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.

curl -s -u samuel:pass123 -X POST http://localhost:8765/api/transfers -H "Content-Type: application/json" -d '{"fromAccount":"BADACCT","toAccount":"NS-100006","amountNgn":-500,"currency":""}'
GlobalExceptionHandler.javaLesson 23 · @RestControllerAdvice
REAL — structured 400{ "timestamp": "2026-04-26T20:37:46.642083", "status": 400, "error": "Validation Failed", "messages": [ "Account must match NS-XXXXXX", "Currency is required", "Amount must be positive" ] }

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.

curl -s -u samuel:pass123 -o /dev/null -w "HTTP %{http_code}" http://localhost:8765/api/transfers/9999
ResponseEntityPatterns.javaLesson 23 · status + headers + body patterns
REAL — 404 for non-existent transferHTTP 404

🔍 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.

curl -s -u samuel:pass123 http://localhost:8765/api/transfers/1001
TransferNotFoundException.java + handlerLesson 23 · domain exception → 404
REAL — successful get, confirming handler doesn't interfere with happy path{ "id": 1001, "fromAccount": "NS-100001", "toAccount": "NS-100002", "amountNgn": 25000.0, "currency": "NGN", "status": "COMPLETED", "createdAt": "2026-04-26T18:37:23.205336" }

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

BuilderStatusUse case
ResponseEntity.ok(body)200Successful GET / PUT with body
ResponseEntity.status(201).body(b)201Resource created (POST)
ResponseEntity.noContent().build()204Successful DELETE, no body
ResponseEntity.badRequest().body(b)400Client error, validation failure
ResponseEntity.notFound().build()404Resource not found
ResponseEntity.status(409).body(b)409Conflict (duplicate, state mismatch)
ResponseEntity.status(500).body(b)500Unhandled server error

🎤 Interview Q&A

EasyWhat is the difference between @ExceptionHandler on a controller vs on a @ControllerAdvice?
+

On a controller it only handles exceptions from that controller. On @ControllerAdvice it handles exceptions from all controllers in the application.

EasyShould I catch exceptions in the service layer or let them propagate?
+

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.

MediumHow do I return different shapes for 4xx vs 5xx errors?
+

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.

MediumHow do I include the request path in the error response?
+

Inject WebRequest or HttpServletRequest into the @ExceptionHandler method. Call request.getDescription(false) or httpRequest.getRequestURI() to get the path.

HardWhat is the order of exception handler resolution in Spring MVC?
+

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

Question 1 of 5
Which annotation makes a class a global exception handler for REST controllers?
Question 2 of 5
What class should you extend to override Spring MVC's built-in exception handling?
Question 3 of 5
What HTTP status code means "resource successfully deleted, no body"?
Question 4 of 5
Which ResponseEntity builder method returns 200 with a body?
Question 5 of 5
What exception does Spring throw when @Valid fails?
0
/ 5
Quiz complete!

Next: Spring Boot Config and Profiles →

⚠️ Common mistakes

Not extending ResponseEntityExceptionHandler
Without it, Spring's default handler returns HTML error pages for validation failures. Extend it and override handleMethodArgumentNotValid.
Returning String from @ExceptionHandler
Without @ResponseBody (implicit in @RestControllerAdvice), a plain String return is treated as a view name. Always return ResponseEntity or ensure @RestControllerAdvice.
Swallowing the cause in a generic handler
A catch-all @ExceptionHandler(Exception.class) that returns "Internal Server Error" without logging ex is useless for debugging. Always log.error("Unhandled", ex).
Handling RuntimeException and Exception without ordering
If RuntimeException handler and Exception handler both exist, the more specific one (RuntimeException) is preferred. But to be explicit, use @Order on advice classes.

✅ 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
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

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 →