Hackforge Academy

Category: java

ControllerAdvice in spring boot

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:

@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:

@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:

@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:

@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:

@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:

@ExceptionHandler(
ResourceNotFoundException.class)
public String handleResourceNotFound(
ResourceNotFoundException ex) {
    return "Requested resource not found";
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community