Exception Handling in Spring Boot using @ControllerAdvice
Introduction :
When developing REST APIs, errors can occur for many reasons. For example, a user may request data that does not exist, submit invalid information, or encounter an unexpected server issue.
If exceptions are not handled properly, the application may return confusing error messages to the client.
Spring Boot provides a powerful mechanism to handle exceptions globally using @ControllerAdvice and @ExceptionHandler.
In this tutorial, we will learn how to:
✅ Create a Custom Exception
✅ Implement Global Exception Handling
✅ Use @ControllerAdvice
✅ Use @ExceptionHandler
✅ Return meaningful error responses to API consumers
Why Do We Need Exception Handling?
Consider the following API:
@GetMapping("/{id}")
public Employee getEmployeeById(@PathVariable Long id) {
return employeeRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Employee not found"));
}
If the employee does not exist, Spring Boot returns a generic error response.
Instead of showing technical errors to users, we should return a clear and meaningful message.
Example:
{
"message": "Employee not found with ID: 10"
}
This improves the API experience and makes debugging easier.
Step 1: Create Custom Exception
Create a class named ResourceNotFoundException.java
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
This exception will be used whenever a requested resource is not found.
Step 2: Use Custom Exception in Service Layer
Update the service method:
public Employee getEmployeeById(Long id) {
return employeeRepository.findById(id)
.orElseThrow(() ->
new ResourceNotFoundException(
"Employee not found with ID: " + id));
}
Now, instead of throwing a generic exception, we throw a custom exception.
Step 3: Create Global Exception Handler
Create a class named GlobalExceptionHandler.java
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleResourceNotFoundException(
ResourceNotFoundException ex) {
return new ResponseEntity<>(
ex.getMessage(),
HttpStatus.NOT_FOUND);
}
}
Explanation
@ControllerAdvice
Allows handling exceptions globally across the application.
@ExceptionHandler
Handles specific exception types and returns custom responses.
Step 4: Test the API
Suppose Employee ID 100 does not exist.
Request:
GET /employees/100
Response:
Employee not found with ID: 100
HTTP Status:
404 NOT FOUND
This response is much cleaner and easier for API consumers to understand.
Benefits of Global Exception Handling
Centralized exception management
Cleaner controller code
Consistent API responses
Better user experience
Easier maintenance
Common Interview Questions
What is @ControllerAdvice?
@ControllerAdvice is used to handle exceptions globally across multiple controllers in a Spring Boot application.
What is @ExceptionHandler?
@ExceptionHandler is used to handle specific exceptions and return custom responses.
Why create custom exceptions?
Custom exceptions provide meaningful error messages and make application logic easier to understand and maintain.
Conclusion :
In this tutorial, we learned how to implement exception handling in Spring Boot using @ControllerAdvice and @ExceptionHandler.
We created:
✅ Custom Exception
✅ Global Exception Handler
✅ Meaningful Error Responses
Exception handling is an important part of building production-ready REST APIs and is commonly used in real-world Spring Boot applications.
In the next tutorial, we will learn how to implement Pagination and Sorting in Spring Boot.
Comments
Post a Comment