Exception Handling in Spring Boot (Deep Dive)
Exception Handling is one of the most important topics in Spring Boot interviews because every real-world application faces errors. Think about these common scenarios:
- User enters invalid data
- Record not found in the database
- Database connection fails
NullPointerExceptionoccurs- External API fails
- Business rule violation occurs
Instead of showing ugly stack traces to users, we handle exceptions properly and return meaningful, structured responses.
1. What is Exception Handling?
Standard Definition
Exception Handling is a mechanism used to handle runtime errors gracefully without terminating the application.
Without Exception Handling
If the user does not exist, a NoSuchElementException occurs, and the user gets an ugly default response:
With Exception Handling
We return something much more user-friendly:
Types of Exception Handling in Spring Boot
- 1. Local Exception Handling: Uses
@ExceptionHandlerto handle exceptions inside a single controller. - 2. Global Exception Handling: Uses
@ControllerAdviceor@RestControllerAdviceto handle exceptions across the entire application. - 3. Custom Exceptions: Standard classes extending
RuntimeExceptionused for business-specific errors (e.g.,UserNotFoundException).
2. Local Exception Handling
Local Exception Handling manages exceptions only inside a specific controller. It is implemented using the @ExceptionHandler annotation.
Implementation Example
Internal Working
When an exception occurs (e.g., throw new RuntimeException()), Spring's DispatcherServlet checks if there is any @ExceptionHandler inside the current controller. If a match is found, it calls the matching handler method.
Note: Handling a superclass like RuntimeException will also automatically handle its subclasses, such as NullPointerException and IllegalArgumentException.
3. Global Exception Handling
The problem with Local Handling is code duplication. If you have UserController, ProductController, and OrderController, you would have to write @ExceptionHandler methods in every single one of them. The solution is Global Exception Handling.
What is @ControllerAdvice?
@ControllerAdvice is a centralized exception handling mechanism that acts as an interceptor to handle exceptions across ALL controllers in your application.
Global Handler Architecture
Example Implementation
4. @RestControllerAdvice
This is a heavily requested interview topic. @RestControllerAdvice is simply a combination of @ControllerAdvice and @ResponseBody.
| Feature | @ControllerAdvice | @RestControllerAdvice |
|---|---|---|
| Returns View | Yes (JSP/HTML) | No |
| Returns JSON/XML | Requires explicit @ResponseBody |
Automatically |
| Primary Use Case | Traditional MVC Apps | REST APIs |
5. Custom Exceptions
Real-world projects rarely throw a generic RuntimeException. Instead, they throw domain-specific exceptions like UserNotFoundException. This greatly improves readability, maintainability, and debugging.
Creating a Custom Exception
Production-Grade Error Response DTO
Instead of returning raw Strings, standard practice dictates returning a structured Data Transfer Object (DTO).
Integrating with the Global Handler
6. Interview Summary Checklist
Top Interview Q&A
Q1: Difference between @ExceptionHandler and @ControllerAdvice?
A: @ExceptionHandler provides local exception handling restricted to a single controller. @ControllerAdvice provides global exception handling that intercepts errors across the entire application.
Q2: Why do Custom Exceptions extend RuntimeException?
A: Extending RuntimeException (an unchecked exception) reduces boilerplate code. It means you don't need to add throws UserNotFoundException to every method signature. The exception propagates automatically up to the global handler without forcing compiler checks.
Q3: Which layer should throw the Custom Exception?
A: Usually the Service Layer. The service layer contains the business logic and knows exactly when a business rule (like "User not found") is violated.
Q4: What is the Global Exception Handling Flow?
A: Client sends request → DispatcherServlet → Controller → Service → Exception occurs → Propagates upward → DispatcherServlet delegates to HandlerExceptionResolver → Spring searches for matching @ExceptionHandler in @RestControllerAdvice → Returns Error Response to client.
Comments
Post a Comment