web layer
Global Exception Handling
Map exceptions to consistent HTTP responses in one place — instead of try/catch in every controller method.
Without a central strategy, error handling scatters try/catch blocks through every controller method, each translating exceptions into HTTP responses slightly differently, and the API ends up with inconsistent status codes and error shapes. Spring's global exception handling consolidates all of that into one place, so every endpoint reports failures uniformly and controllers stay focused on the happy path.
A help desk that catches every kind of complaint and routes it to the right response, instead of every department writing their own form letter.
Key Concepts
1
The mechanism is @RestControllerAdvice (or @ControllerAdvice), a class whose @ExceptionHandler methods catch exceptions thrown by any controller in the application. Each handler method declares the exception type it handles and returns a ResponseEntity with the appropriate status and a structured error body — a 404 for a NotFoundException, a 400 for validation failures, a 409 for a conflict, and a catch-all 500 for anything unexpected. You map your domain exceptions to HTTP semantics here, in a single class, and you can produce a consistent error contract — a JSON object with a code, message, timestamp, and field details — that every client can rely on. Spring 6 also offers the ProblemDetail type for standardised RFC 7807 error responses.
@RestControllerAdvice@ControllerAdvice@ExceptionHandlerResponseEntityNotFoundException
2
The points that distinguish a strong answer are choosing status codes that match the failure's meaning, never leaking internal details like stack traces or SQL into the response body, and ordering handlers from specific to general so a precise handler wins over the catch-all. It also pairs naturally with validation — the same advice class typically handles MethodArgumentNotValidException — giving you one coherent place that defines how the whole API fails.
MethodArgumentNotValidException