Exception Handling
Orders should fail with a stable JSON error shape, not a stack trace HTML page.
Introduction
Orders should fail with a stable JSON error shape, not a stack trace HTML page. On Boot 3, @ControllerAdvice plus ProblemDetail (RFC 9457) is the modern default path.
Throw domain exceptions from the service (OrderNotFoundException, OrderConflictException). Advice maps them to status codes and problem details. Controllers stay free of try/catch noise.
Validation failures from @Valid become MethodArgumentNotValidException — handle them once in advice.
Never return raw exception messages that leak SQL or file paths to clients.
Purpose of this lesson
Centralize Orders error translation with @ControllerAdvice and ProblemDetail-style responses.
Understanding the topic
Exceptions are part of the API if clients can see them.
- Domain exceptions: express business failures.
- @ExceptionHandler: per-advice methods for types you care about.
- ProblemDetail: type, title, status, detail, instance — keep detail safe.
- Fallback: generic 500 handler that logs fully and returns a opaque id.
- No stack traces in production responses.
Step-by-step explanation
- Create
OrderNotFoundException. - Throw it from
OrderService.get. - Add
@RestControllerAdvicemapping it to 404 ProblemDetail. - Confirm
server.error.include-stacktrace=neverin config.
Informative example
Not-found advice.
@RestControllerAdvicepublic class OrdersExceptionHandler {@ExceptionHandler(OrderNotFoundException.class)ProblemDetail notFound(OrderNotFoundException ex) {ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.NOT_FOUND);pd.setTitle("Order not found");pd.setDetail("No order exists for the given id.");return pd;}}
Real-world use
Support engineers correlate client error bodies with server logs via a correlation id. TechLearningPRO Orders should log the stack once server-side and return a short, safe detail to the app.
Security implications
Error bodies are an information channel.
- Pin stacktrace inclusion to never in prod.
- Do not reveal whether an email exists via differing error messages if that matters.
- Log thoroughly; respond minimally.
Best practices
- One advice class (or a small set) for HTTP APIs.
- Map domain exceptions explicitly; do not overuse generic handlers.
- Include a correlation id header/body field when you have tracing.
Common mistakes
- Catching Exception in every controller method.
- Returning
ex.getMessage()from JDBC exceptions. - Inconsistent error JSON per endpoint.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhat is @ControllerAdvice for?+
Answer
2IntermediateQuestionWhat is ProblemDetail in Boot 3?+
Answer
3IntermediateQuestionWhy not expose SQLException messages?+
Answer
Hands-on exercise
Lab. Throw OrderNotFoundException and return ProblemDetail 404. Force a generic exception and ensure the client does not receive a stack trace.
Summary
Stable Orders errors come from advice, not ad-hoc catches. Next you validate inputs before the service runs.