Exception Handling with @ControllerAdvice — Spring Technical Interview Questions & Answers
Centralized error handling across controllers.
Exception Handling with @ControllerAdvice
- @ControllerAdvice is a global place to handle exceptions for many controllers.
- @ExceptionHandler methods catch a type and build the response.
- Keeps controllers focused on happy-path logic.
- Works for MVC and REST style apps.
- Global exception handling = consistent API errors.
Technical Interview Tip: Explain advice + handler pair with one exception type.
Code Examples for Exception Handling with @ControllerAdvice
Exception Handling with @ControllerAdvice — working example
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestControllerAdvice
class ApiErrors {
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
Map<String, String> badRequest(IllegalArgumentException ex) {
return Map.of("error", ex.getMessage());
}
}
record CreateUserRequest(@NotBlank @Email String email) {}
@RestController
class Users {
@PostMapping("/users")
User create(@Valid @RequestBody CreateUserRequest req) {
return new User(req.email());
}
}Exception Handling with @ControllerAdvice — @RestControllerAdvice centralizes API errors; @Valid triggers bean validation on DTOs.
How to Explain Exception Handling with @ControllerAdvice to an Interviewer
What is Exception Handling with @ControllerAdvice (sb misc)?
Used for GET /api/marks/{roll} a campus API Not just the heading
Give one small example of Exception Handling with @ControllerAdvice (sb misc).
@RestController + service call Centralized error handling across controllers
What mistake do beginners make with Exception Handling with @ControllerAdvice (sb misc)?
business logic inside the controller Show the fix
Where do you use Exception Handling with @ControllerAdvice (sb misc)?
a campus API GET /api/marks/{roll}