VOOZH about

URL: https://www.geeksforgeeks.org/springboot/exception-handling-in-spring-boot/

⇱ Exception Handling in Spring Boot - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Exception Handling in Spring Boot

Last Updated : 29 Apr, 2026

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 to Exception Handling in Spring Boot

Here are some key approaches to exception handling in Spring Boot:

  • Default exception handling by Spring Boot
  • Using @ExceptionHandler annotation
  • Using @ControllerAdvice for global exception handling

Spring Boot Exception Handling Simple Example Project

Let's do the initial setup to explore each approach in more depth.

Initial Setup

To create a simple Spring Boot project using Spring Initializer, please refer to this article. Now let's develop a Spring Boot RESTful web service that performs CRUD operations on a Customer Entity. We will be using a MYSQL database for storing all necessary data.

Step 1: Creating a JPA Entity Class Customer

We will create a Customer class, which represents the entity for our database. The class is annotated with @Entity.

Explanation: This class represents a JPA entity used to store customer details in a database table. It uses Lombok annotations to reduce boilerplate code by generating getters, setters, and constructors automatically.

Step 2: Creating a CustomerRepository Interface

Next, we create the repository interface for CRUD operations on the Customer entity. This interface extends JpaRepository, which provides built-in methods for data access.

Note: The CustomerRepository interface is annotated with @Repository annotation and extends the JpaRepository of Spring Data JPA .

Step 3: Creating Custom Exceptions

Now, we will create two custom exceptions:

CustomerAlreadyExistsException: This exception can be thrown when the user tries to add a customer that already exists in the database.

NoSuchCustomerExistsException: This exception can be thrown when the user tries to delete or update a customer record that doesn't exist in the database.

Note: Both Custom Exception classes extend RuntimeException.

Step 4: Creating the Service Layer

The CustomerService interface defines three different methods:

  • Customer getCustomer(Long id): To get a customer record by its id. This method throws a NoSuchElementException exception when it doesn't find a customer record with the given id.
  • String addCustomer(Customer customer): To add details of a new Customer to the database. This method throws a CustomerAlreadyExistsException exception when the user tries to add a customer that already exists.
  • String updateCustomer(Customer customer): To update details of Already existing Customers. This method throws a NoSuchCustomerExistsException exception when the user tries to update details of a customer that doesn't exist in the database.

The Interface and service implementation class is as follows:

CustomerService Interface:

CustomerServiceImpl Implementation:

Step 5: Creating the CustomerController

The controller exposes RESTful endpoints for customer-related operations. The methods in this class will throw exceptions, which we will handle using various exception handling techniques.

Handling Exceptions in Spring Boot

Now let's go through the various ways in which we can handle the Exceptions thrown in this project.

1. Default Exception Handling by Spring Boot

The getCustomer() method defined by CustomerController is used to get a customer with a given Id. It throws a NoSuchElementException when it doesn't find a Customer record with the given id. On Running the Spring Boot Application and hitting the /getCustomer API with an Invalid Customer Id, we get a NoSuchElementException completely handled by Spring Boot as follows:

👁 getCustomer API Testing

Spring Boot provides a systematic error response to the user with information such as timestamp, HTTP status code, error, message, and the path.

2. Using @ExceptionHandler Annotation

  • @ExceptionHandler annotation provided by Spring Boot can be used to handle exceptions in particular Handler classes or Handler methods.
  • Any method annotated with this is automatically recognized by Spring Configuration as an Exception Handler Method.
  • An Exception Handler method handles all exceptions and their subclasses passed in the argument.
  • It can also be configured to return a specific error response to the user.

So let's create a custom ErrorResponse class so that the exception is conveyed to the user in a clear and concise way as follows:


The addCustomer() method defined by CustomerController throws a CustomerAlreadyExistsException when the user tries to add a Customer that already exists in the database else it saves the customer details.

To handle this exception let's define a handler method handleCustomerAlreadyExistsException() in the CustomerController. So, now when addCustomer() throws a CustomerAlreadyExistsException, the handler method gets invoked which returns a proper ErrorResponse to the user.

Note : Spring Boot allows to annotate a method with @ResponseStatus to return the required Http Status Code.

On Running the Spring Boot Application and hitting the /addCustomer API with an existing Customer, CustomerAlreadyExistsException gets completely handled by handler method as follows:

👁 addCustomer API Testing

3. Using @ControllerAdvice for Global Exception Handling

  • @ControllerAdvice is used to handle exceptions globally across all controllers in a Spring Boot application. It allows you to define a centralized exception handling mechanism instead of writing separate handlers in each controller.
  • @ControllerAdvice alone does not automatically handle all exceptions. You must use @ExceptionHandler(ExceptionClass.class) to specify which exception a particular method should handle. Each handler method is responsible for handling a specific type of exception.

The updateCustomer() method in the CustomerController throws a NoSuchCustomerExistsException when a user tries to update a customer that does not exist in the database. To handle this exception globally, we define a separate class annotated with @ControllerAdvice.

On running the Spring Boot application and hitting the /updateCustomer API with invalid customer details, NoSuchCustomerExistsException gets thrown, which is completely handled by the handler method defined in the GlobalExceptionHandler class as follows:

👁 updateCustomer API Testing

Comment

Explore