Controller advice centralizes web-layer error mapping. Preserve domain meaning while keeping implementation details out of responses.
Before you start
You should know Java classes, dependency injection and basic HTTP requests. Identify where a call crosses a framework-managed boundary. The snippets illustrate a focused mechanism; database configuration, application wiring and authentication must be supplied by the surrounding application when applicable.
The practical goal is to reason through this situation: Map a known not-found exception to a documented response status and payload. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.
Step-by-step walkthrough
Step 1: Define public failure contracts
Map known exceptions to documented status codes and payloads.
Step 2: Centralize web mapping
Use controller advice while retaining the underlying domain distinction.
Step 3: Keep unexpected detail internal
Return a safe server error and correlation ID while recording diagnostic context.
Worked scenario
Map a known not-found exception to a documented response status and payload.
A missing invoice returns a not-found outcome; an unavailable database returns a server failure. Mapping both to 200 with an error string makes clients and monitoring misinterpret success. The advice controls HTTP representation without converting every exception into the same business result.
Common mistake
Mapping every exception to 200 makes monitoring and clients misinterpret failure.
Verify the behavior
Assert status, safe payload and correlation behavior for known and unexpected failures.
Interview exercise
Handle an unexpected database error.
Answer and reasoning
Return a safe server error with a correlation identifier and record detailed diagnostics internally.
Continue learning
Compare the scenario with the Spring Boot interview questions and test your understanding with the Spring Boot MCQs. For terminology and implementation details, consult the reference material.