Spring MVC – @ControllerAdvice Annotation for Global Exception Handling
Last Updated :
23 Jul, 2025
In a Spring MVC application, managing exceptions effectively is important to providing a smooth user experience. When exceptions occur, users should receive clear and meaningful error messages instead of confusing stack traces.
Spring MVC offers multiple approaches to handle exceptions, such as per-controller exception handling and global exception handling. The @ControllerAdvice
annotation provides a way to centralize exception handling across the entire application, helping developers write cleaner and more maintainable code.
Prerequisites:
- Basic knowledge of the Java and Spring Framework.
- The concept of exception handling in Java.
- RESTful web services (if you’re building REST APIs).
- Maven for building dependency management.
- JDK and IntelliJ IDEA installed in your system.
@ControllerAdvice Annotation for Global Exception Handling in Spring MVC
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 as a global handler for exceptions thrown by any controller method.
This annotation works like Aspect-Oriented Programming (AOP), intercepting exceptions thrown by controllers and handling them with methods defined in the @ControllerAdvice
class.
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.
How it Works:
- 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 in Spring MVC with @ControllerAdvice
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:
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:
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.
Java
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
<?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.
Similar Reads
Spring WebFlux Rest API Global Exception Handling Spring WebFlux is part of Spring Framework, allowing us to Reactive programming and Support non-blocking I/O operations. The Spring Framework provides a lot of Annotations to handle the applications. This article focuses on Global Exception Handling by using Rest API in the Spring WebFlux. For this,
6 min read
Difference Between @Controller and @RestController Annotation in Spring Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not directly affect the operation of the code they annotate. It does not change the action of the compiled program. Understanding the differ
3 min read
Spring MVC - Exception Handling When something goes wrong in your app, the server shows a default error page, which isnât user-friendly. Spring MVC lets you handle exceptions in a cleaner way using the @ExceptionHandler annotation. It allows you to show custom error pages based on specific exceptions, either at the method or class
5 min read
BeanDefinitionOverrideException in Spring Boot The BeanDefinitionOverrideException is a type of exception in Spring Boot. This occurs in Spring Boot when we try to override a bean definition that already exists in our application. If we have two beans with the same name, Spring throws an exception to prevent developers from overriding the existi
3 min read
Exception Handling in Spring Boot Exception handling in Spring Boot helps deal with errors and exceptions present in APIs, delivering a robust enterprise application. This article covers various ways in which exceptions can be handled and how to return meaningful error responses to the client in a Spring Boot Project. Key Approaches
8 min read
Spring Boot @Controller Annotation with Example Spring is one of the most popular frameworks for building enterprise-level Java applications. It is an open-source, lightweight framework that simplifies the development of robust, scalable, and maintainable applications. Spring provides various features such as Dependency Injection (DI), Aspect-Ori
3 min read