How does exception handling work in Spring MVC with @ControllerAdvice?
Learn how @ControllerAdvice centralizes Spring MVC exception handling, maps exceptions to HTTP status codes, and returns consistent JSON error responses.
Expected Interview Answer
@ControllerAdvice is a global exception handler in Spring MVC: a class annotated with it defines @ExceptionHandler methods that apply across all controllers, letting you centralize error handling instead of repeating try/catch in every controller.
When a controller method throws an exception, Spring searches for a matching @ExceptionHandler, first on the controller itself and then in any @ControllerAdvice class, and invokes the most specific match. These handlers can return a ResponseEntity with a chosen HTTP status and body, and @RestControllerAdvice adds @ResponseBody so the returned object is serialized directly to JSON. You typically build a consistent error-response shape and map exception types to status codes there.
- Centralizes error handling in one place
- Removes repetitive try/catch from controllers
- Produces consistent, structured error responses
- Maps exception types to correct HTTP status codes
- Keeps controllers focused on the happy path
AI Mentor Explanation
Think of a third umpire who handles every disputed decision from all on-field umpires in one central booth, instead of each umpire improvising. A controller's thrown exception is the disputed call, and @ControllerAdvice is that central review booth applying one consistent ruling across the whole match rather than scattered ad hoc decisions.
Step-by-Step Explanation
Step 1
Create the advice class
Annotate a class with @ControllerAdvice (or @RestControllerAdvice for JSON APIs).
Step 2
Define handler methods
Add methods annotated with @ExceptionHandler(SomeException.class) to handle specific exception types.
Step 3
Build the response
Return a ResponseEntity with the right HttpStatus and a structured error body.
Step 4
Let Spring resolve
On a thrown exception Spring picks the most specific matching handler, checking the controller then the advice.
Step 5
Add validation handling
Handle MethodArgumentNotValidException to turn bean-validation failures into clean 400 responses.
What Interviewer Expects
- Difference between @ControllerAdvice and @RestControllerAdvice
- How @ExceptionHandler methods are matched by exception type
- Returning correct HTTP status codes via ResponseEntity
- Order of resolution: controller-local before global advice
- Designing a consistent error-response body
Common Mistakes
- Using @ControllerAdvice but forgetting @ResponseBody for JSON APIs
- Catching a too-broad Exception and hiding specific error causes
- Returning 200 OK for actual error conditions
- Not handling validation exceptions like MethodArgumentNotValidException
- Assuming global advice overrides a controller-local handler for the same exception
Best Answer (HR Friendly)
“@ControllerAdvice lets a Spring application handle errors in one central place instead of writing error-catching code in every controller. When something goes wrong, it produces a consistent, well-formatted response with the right status code, which keeps the code clean and the API predictable.”
Code Example
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
ErrorResponse body = new ErrorResponse("NOT_FOUND", ex.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(body);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex) {
String msg = ex.getBindingResult().getFieldError().getDefaultMessage();
return ResponseEntity.badRequest().body(new ErrorResponse("VALIDATION_ERROR", msg));
}
}Follow-up Questions
- What is the difference between @ControllerAdvice and @RestControllerAdvice?
- How do you return a custom JSON error body with a specific status?
- How does Spring decide which @ExceptionHandler to invoke?
- How do you handle bean-validation errors globally?
- What is ResponseEntityExceptionHandler and when do you extend it?
MCQ Practice
1. What does @RestControllerAdvice add over @ControllerAdvice?
@RestControllerAdvice combines @ControllerAdvice with @ResponseBody, so handler return values are written directly to the response body as JSON.
2. Where does Spring look first for an @ExceptionHandler?
Spring checks controller-local @ExceptionHandler methods first and falls back to global @ControllerAdvice handlers.
3. Which exception is handled to catch @Valid request-body failures?
Failed bean validation on a @RequestBody argument throws MethodArgumentNotValidException, which you handle to return a 400.
Flash Cards
What is @ControllerAdvice? — A class-level annotation that defines global @ExceptionHandler, @InitBinder, and @ModelAttribute methods shared across controllers.
@ControllerAdvice vs @RestControllerAdvice? — @RestControllerAdvice adds @ResponseBody, serializing handler returns to JSON for REST APIs.
How are exceptions matched? — Spring picks the most specific @ExceptionHandler, checking the throwing controller first, then global advice.
How to set the HTTP status? — Return a ResponseEntity with the chosen HttpStatus, or annotate the handler with @ResponseStatus.
How to handle validation errors? — Add an @ExceptionHandler for MethodArgumentNotValidException and return a 400 with field messages.
Continue Learning
Related Interview Questions
What is the difference between @Controller and @RestController in Spring?
easy
What is the DispatcherServlet and how does the Spring MVC request flow work?
medium
How does Spring Boot embed a web server and how does the embedded Tomcat work?
medium
What is dependency injection in Spring and how does the IoC container work?
medium