Category: React • Beginner
Published on 06 Apr 2026
Explanation
@ControllerAdvice is a Spring Boot annotation used for global exception handling across the entire application. Instead of writing error-handling logic inside every controller, it centralizes the logic in one place.
Code Example
@ControllerAdvice
public class GlobalExceptionHandler {
}
Explanation
It improves code reusability and maintainability by handling exceptions globally rather than repeating try-catch blocks inside each controller method.
Code Example
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public String handleException(
Exception ex) {
return "Something went wrong";
}
}
Explanation
@ExceptionHandler annotation is used inside @ControllerAdvice to catch specific exceptions and return custom responses.
Code Example
@ExceptionHandler(NullPointerException.class)
public String handleNullPointerException(
NullPointerException ex) {
return "Null value found";
}
Explanation
In REST APIs, @RestControllerAdvice is commonly used instead of @ControllerAdvice because it automatically returns JSON responses instead of view pages.
Code Example
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public String handleRuntimeException(
RuntimeException ex) {
return "Runtime error occurred";
}
}
Explanation
@ControllerAdvice can also handle validation errors globally when using DTO validation with @Valid annotation.
Code Example
@ExceptionHandler(
MethodArgumentNotValidException.class
)
public String handleValidationException(
MethodArgumentNotValidException ex) {
return "Validation failed";
}
Explanation
@ControllerAdvice is especially useful in large applications such as student management systems or training platforms like your Spring Boot APIs, where consistent error responses improve frontend integration and debugging 🚀.
Code Example
@ExceptionHandler(
ResourceNotFoundException.class)
public String handleResourceNotFound(
ResourceNotFoundException ex) {
return "Requested resource not found";
}