Spring MVC – @ControllerAdvice Annotation for Global Exception Handling
Last Updated :
21 Oct, 2024
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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read