SpringBoot Rest API Error Handling
Proper error handling in a Spring Boot REST API is essential for building a robust, user-friendly, and maintainable application. Spring Boot offers helpful error messages for developers building REST APIs. However, these messages are not always useful for general API consumers. This article present a straightforward approach to enhance this functionality.
Introduction
Let assume we have an ecommerce application and have following set of Rest API to deal with catalog.
GET /catalog/product/{productId} | To get product based on product Id |
Below is the controller class for same. We use CatalogManager to get the products.
package com.example.prepkaro;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value = "/catalog")
public class CatalogController {
@Autowired
CatalogManager catalogManager;
@GetMapping(value = "/product/{productId}")
public Product getProduct(@PathVariable String productId) {
return catalogManager.getProduct(productId);
}
}
CatalogManager class has method getProduct which help to fetch product from Database and return ProductNotFoundException in case product is not found.
Let say we make following get request with product Id as 1. Below is success response from API
.

.
Spring Default Behavior
Above we saw successful response with status code as 200 OK. Lets try to pass product Id 2 , which do not exist in Database. In that case our application will throw ProductNotFoundException . This is custom exception defined extending Runtime exception
public class ProductNotFoundException extends RuntimeException{
public ProductNotFoundException(String message) {
super(message);
}
}
Below is how SpringBoot will return the response without proper error handling in place.

The default response generated by DefaultErrorAttributes
in Spring Boot includes some useful fields but is heavily centered on the exception itself. The timestamp
field is an integer without a clear indication of its measurement unit, the exception
field is only meaningful to Java developers, and the message
often overwhelms API consumers with unnecessary implementation details. But what if we could extract more meaningful information from exceptions? Let’s explore how to properly handle exceptions in Spring Boot and structure them into a more user-friendly JSON response, making life easier for our API clients.
How to return a clear error Response ?
The Spring Framework’s MVC module provides powerful error-handling features. However, it is up to developers to leverage these features to handle exceptions effectively and deliver meaningful responses to API clients. There are two ways in which once can error handle error gracefully.
- Local or Controller Level exception handling
- Global exception handling
Local or Controller Level – @ExceptionHandler Annotation
When a method is annotated with @ExceptionHandler
, Spring automatically detects it and registers the method as an exception handler for the specified exception class and its subclasses.
@RestController
@RequestMapping(value = "/catalog")
public class CatalogController {
@Autowired
CatalogManager catalogManager;
@GetMapping(value = "/product/{productId}")
public Product getProduct(@PathVariable String productId) {
return catalogManager.getProduct(productId);
}
@ExceptionHandler(value = ProductNotFoundException.class)
protected ResponseEntity<Object> handleProductNotFoundException(
RuntimeException ex, WebRequest request) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
We have added a new method handleProductNotFoundException annotated with @ExceptionHandler(value = ProductNotFoundException.class)
Let try to hit the API again with invalid product Id

Now we have proper Error message and status code. This could be improved further by creating a custom Error class and populating it with more details.
This approach is good but , you class can get bulky if you add more exception handlers. It also violates Single Responsibility principle. Let see how this could be solved using Global exception handling.
Global Exception Handling
Spring introduces support for a global @ExceptionHandler
using the @ControllerAdvice
annotation. @ControllerAdvice
is a Spring annotation that provides a centralized way to handle exceptions across multiple controllers. As the name suggests, it acts as “advice” for controllers, allowing a single @ExceptionHandler
to be applied globally. By using this annotation, we can define exception-handling logic in one place, ensuring that any covered controllers trigger the specified handler when an exception occurs.
@ControllerAdviceAnnotation
Extending our previous example, instead of defining exception hander in controller class, we can create a new class and annotate it with @ControllerAdvice.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = ProductNotFoundException.class)
protected ResponseEntity<Object> handleProductNotFoundException(
RuntimeException ex, WebRequest request) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
ResponseEntityExceptionHandler Class
ResponseEntityExceptionHandler is a convenience base class provided by Spring that simplifies exception handling for REST APIs. It contains predefined exception handlers that handle common exceptions automatically, ensuring consistent and structured error responses.
Summary
This article discussed exception handling for SpringBoot Rest. It presented default behavior and how to return a proper error response with Local and Global Exception handling.