Spring MVC provides several ways to handle exceptions, such as per-controller exception handling and global exception handling. The @ControllerAdvice annotation enables us to centralize exception handling across the entire application, resulting in cleaner, reusable and easier-to-maintain code.
What is @ControllerAdvice
@ControllerAdvice is a specialized annotation introduced in Spring 3.2 that enables global exception handling across your entire Spring MVC application. It acts like Aspect-Oriented Programming (AOP), intercepting exceptions thrown by controllers.
Key Features of @ControllerAdvice
- Global Exception Handling: It allows handling exceptions across multiple controllers, enabling centralized management.
- Reusable Logic: Instead of repeating exception handling logic in each controller, you define it once in a single class.
- Custom Error Responses: You can return customized error messages or formats (e.g., JSON responses in REST APIs).
How Does @ControllerAdvice Work
The main purpose of @ControllerAdvice is to group and manage multiple exception handlers in one global location. It uses the @ExceptionHandler annotation to map specific exceptions to the methods that handle them.
- Exception Occurs: When an exception is thrown during the execution of a controller method, Spring looks for an appropriate @ExceptionHandler method in @ControllerAdvice.
- Exception Matches: If the exception matches the type handled by the @ExceptionHandler, that method is executed.
- Custom Response: The @ExceptionHandler method returns a custom error response (e.g., an error message, status code or data).
Implementation of Global Exception Handling
Let's walk through a sample project demonstrating how to implement global exception handling using the @ControllerAdvice annotation.
Step 1: Create a New Spring Boot Project
Create a new Spring Boot project using IntelliJ IDEA or Spring Initializr with the following options:
- Name: spring-mvc-exception-handling
- Language: Java
- Type: Maven
- Packaging: Jar
Click on the Next button.

Step 2: Add the Dependencies
Add the following dependencies into the Spring Boot Project:
- Spring Web (for building web applications)
- Lombok (for reducing boilerplate code)
- Spring DevTools (for development convenience)
Click on the Create button.

Project Structure
Once the project is created, set up the file structure like below:

Step 3: Configure Application Properties
Set up the application.properties file:
spring.application.name=spring-mvc-exception-handling
server.port=8080
Step 4: Create the UserController Class
The UserController class handles requests related to users. If the user ID provided is invalid, it throws an exception.
UserController.java:
package com.gfg.springmvcexceptionhandling;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController // Marks the class as a RESTful controller
public class UserController {
// Endpoint to fetch user by ID
@GetMapping("/user/{id}")
public String getUserById(@PathVariable int id) {
// If the ID is negative, throw an IllegalArgumentException
if (id < 0) {
throw new IllegalArgumentException("Invalid user ID: " + id);
}
// Return user information if ID is valid
return "User with ID: " + id;
}
}
Explanation:
- UserController defines a GET endpoint /user/{id} that accepts a user ID.
- If the user ID is negative, it throws an IllegalArgumentException, which will be handled globally by @ControllerAdvice.
Step 5: Create the GlobalExceptionHandler Class
This class, annotated with @ControllerAdvice, contains methods to handle exceptions globally in the Spring Boot application.
GlobalExceptionHandler.java:
package com.gfg.springmvcexceptionhandling;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice // Global exception handler for all controllers
public class GlobalExceptionHandler {
// Method to handle IllegalArgumentException
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException ex) {
// Return a custom error message with HTTP 400 status
return new ResponseEntity<>("Error: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
}
// Method to handle generic exceptions
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGeneralException(Exception ex) {
// Return a custom error message with HTTP 500 status
return new ResponseEntity<>("An unexpected error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Explanation:
- @ControllerAdvice enables global exception handling for all controllers in the application.
- handleIllegalArgumentException() handles IllegalArgumentException and returns a custom error message with a 400 (Bad Request) status.
- handleGeneralException() catches any other exceptions and returns a generic error message with a 500 (Internal Server Error) status.
Step 6: Main Class
No changes are required in the main class.
package com.gfg.springmvcexceptionhandling;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // Marks the application as a Spring Boot application
public class SpringMvcExceptionHandlingApplication {
public static void main(String[] args) {
SpringApplication.run(SpringMvcExceptionHandlingApplication.class, args);
}
}
pom.xml File
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gfg</groupId>
<artifactId>spring-mvc-exception-handling</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-mvc-exception-handling</name>
<description>spring-mvc-exception-handling</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 7: Run the Application
Run the application, which will start on port 8080 as specified in application.properties.

Step 8: Testing the Application
We will now test the application using the Postman tool.
1. Valid User ID
Request: http://localhost:8080/user/1
Response:

2: Invalid User ID (Negative)
Request: http://localhost:8080/user/-1
Response:

3: Generic Exception Handling (Invalid ID Format)
If we throw the generic exception in the another part of the application (which is not specific to IllegalArgumentException), the second handler (handleGeneralException) will catch it and return a 500 status.
Request: http://localhost:8080/user/-1a
Response:

This example project demonstrates how to implement the global exception handling in the Spring MVC application using the @ControllerAdvice annotation. We created the UserController that throws exceptions and the GlobalExceptionHandler to handle them globally.