@ControllerAdvice lets you centralize exception handling for every controller in a Spring MVC application in one place, instead of duplicating try/catch logic across each controller. Methods inside a @ControllerAdvice class are annotated with @ExceptionHandler to declare which exception types they respond to.
Key Points: • A class annotated @ControllerAdvice is automatically applied across all @Controller and @RestController beans in the application. • @ExceptionHandler(SomeException.class) on a method within that class catches that exception type whenever it's thrown from any controller. • Handler methods can return a ResponseEntity with a specific status code and structured error body, which is especially useful for REST APIs. • @RestControllerAdvice combines @ControllerAdvice and @ResponseBody, so exception handler methods can return serialized error objects directly, matching @RestController's style. • Multiple @ExceptionHandler methods can be defined for different exception types, and a catch-all handler for generic Exception is common as a last resort.
Example: A ResourceNotFoundException thrown from any service layer could be caught by a single handler in a @RestControllerAdvice class, returning a 404 status with a consistent JSON error body across the entire API instead of each controller handling it separately.
Code Example:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ErrorResponse(ex.getMessage()));
}
}Interview Tip: A concise interview answer is:
"I create a class annotated @RestControllerAdvice with @ExceptionHandler methods for specific exception types, so any controller in the app that throws those exceptions gets handled the same way. This keeps error responses consistent across the API instead of scattering try/catch blocks throughout individual controllers."