Why Centralized Error Handling Matters in Spring Boot
📖 Scenario: You are building a simple Spring Boot web application that manages user profiles. You want to make sure that when errors happen, your app handles them in one place so it is easier to maintain and users get clear messages.
🎯 Goal: Build a Spring Boot project that shows how to centralize error handling using @ControllerAdvice and @ExceptionHandler. This will catch errors from any controller and return a friendly message.
📋 What You'll Learn
Create a custom exception class called UserNotFoundException.
Create a controller class called UserController with a method that throws UserNotFoundException.
Create a centralized error handler class called GlobalExceptionHandler using @ControllerAdvice.
Add a method in GlobalExceptionHandler annotated with @ExceptionHandler(UserNotFoundException.class) to handle the exception and return a custom response.
💡 Why This Matters
🌍 Real World
Centralized error handling is used in real web applications to manage errors in one place, making maintenance easier and improving user experience by providing consistent error messages.
💼 Career
Understanding centralized error handling is important for backend developers working with Spring Boot or similar frameworks, as it is a common pattern in professional web development.
Progress0 / 4 steps
1
Create the custom exception class
Create a public class called UserNotFoundException that extends RuntimeException. Add a constructor that accepts a String message and passes it to the superclass.
Spring Boot
Hint
Think of this class as a special kind of error that you can throw when a user is not found.
2
Create the UserController with a method that throws the exception
Create a class called UserController annotated with @RestController. Add a method getUserById that takes a Long id parameter and throws new UserNotFoundException("User not found").
Spring Boot
Hint
This controller simulates a user lookup that always fails by throwing your custom exception.
3
Create the GlobalExceptionHandler class with @ControllerAdvice
Create a class called GlobalExceptionHandler annotated with @ControllerAdvice. This class will hold methods to handle exceptions globally.
Spring Boot
Hint
This class will catch exceptions from all controllers in one place.
4
Add an @ExceptionHandler method for UserNotFoundException
Inside GlobalExceptionHandler, add a method handleUserNotFoundException annotated with @ExceptionHandler(UserNotFoundException.class). It should accept a UserNotFoundException parameter and return a String with the exception message.
Spring Boot
Hint
This method catches the exception and returns its message as the response.
Practice
(1/5)
1. Why is centralized error handling important in a Spring Boot application?
easy
A. It requires writing error handling code in every controller separately.
B. It automatically fixes all bugs without developer intervention.
C. It allows handling all exceptions in one place for cleaner code and easier maintenance.
D. It disables error messages to users for security reasons.
Centralized error handling groups exception logic in one place, avoiding repetition.
Step 2: Compare with other options
Options B and C are incorrect because errors are not fixed automatically, and error messages can be customized but not disabled by default. It requires writing error handling code in every controller separately. is incorrect because centralized handling avoids writing error code in every controller separately.
Final Answer:
It allows handling all exceptions in one place for cleaner code and easier maintenance. -> Option C
Hint: Remember: Advice means giving guidance globally [OK]
Common Mistakes:
Using @RestController for error handling
Confusing @Service with error handling
Thinking @Repository handles exceptions
3. Given this Spring Boot code snippet inside a @ControllerAdvice class:
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<String> handleNullPointer() {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Null value found");
}
What will be the HTTP status code and message when a NullPointerException occurs?
medium
A. 400 Bad Request with message "Null value found"
B. 200 OK with message "Null value found"
C. 500 Internal Server Error with default message
D. 404 Not Found with message "Null value found"
Solution
Step 1: Analyze the @ExceptionHandler method
The method returns ResponseEntity with status BAD_REQUEST (400) and body "Null value found" when NullPointerException occurs.
Step 2: Match status and message to options
400 Bad Request with message "Null value found" matches 400 Bad Request and the custom message. Other options have wrong status codes or messages.
Final Answer:
400 Bad Request with message "Null value found" -> Option A
Quick Check:
@ExceptionHandler sets status 400 and message [OK]
Hint: Check ResponseEntity status for HTTP code [OK]
Common Mistakes:
Assuming default 500 error instead of custom status
Confusing 404 Not Found with exception handling
Ignoring the custom message in response body
4. Consider this @ControllerAdvice class snippet:
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleAll(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred");
}
Why might this cause problems in a Spring Boot app?
medium
A. It only handles NullPointerExceptions, ignoring other exceptions.
B. It returns 200 OK status instead of error status.
C. It causes syntax errors because @ExceptionHandler cannot handle Exception class.
D. It catches all exceptions, hiding specific error handlers and making debugging harder.
Handling Exception.class catches all exceptions, which can override more specific handlers and hide detailed error info.
Step 2: Evaluate other options
It only handles NullPointerExceptions, ignoring other exceptions. is wrong because it handles all exceptions, not just NullPointerException. It causes syntax errors because @ExceptionHandler cannot handle Exception class. is incorrect; syntax is valid. It returns 200 OK status instead of error status. is wrong; status is 500, not 200.
Final Answer:
It catches all exceptions, hiding specific error handlers and making debugging harder. -> Option D
Quick Check:
Generic Exception handler can hide specific errors [OK]
Hint: Generic handlers override specific ones, use carefully [OK]
Common Mistakes:
Thinking it only handles NullPointerException
Believing it causes syntax errors
Assuming it returns 200 OK status
5. You want to create a centralized error handler that returns different HTTP statuses for different exceptions: 404 for ResourceNotFoundException and 400 for InvalidInputException. Which approach correctly implements this in Spring Boot?
hard
A. Use one @ExceptionHandler method with multiple if-else checks on exception type inside it.
B. Create separate @ExceptionHandler methods for each exception type inside a @ControllerAdvice class.
C. Handle exceptions inside each controller method instead of centralized handling.
D. Use @ControllerAdvice with a single method annotated with @ExceptionHandler(Exception.class) returning 200 OK.
Solution
Step 1: Understand best practice for multiple exception types
Spring Boot recommends separate @ExceptionHandler methods for each exception type to return specific responses clearly.
Step 2: Evaluate other options
Use one @ExceptionHandler method with multiple if-else checks on exception type inside it. is less clean and harder to maintain. Handle exceptions inside each controller method instead of centralized handling. defeats centralized handling purpose. Use @ControllerAdvice with a single method annotated with @ExceptionHandler(Exception.class) returning 200 OK. returns wrong status 200 OK and handles all exceptions generically.
Final Answer:
Create separate @ExceptionHandler methods for each exception type inside a @ControllerAdvice class. -> Option B
Quick Check:
Separate handlers per exception = clear, maintainable [OK]
Hint: One handler per exception type for clarity [OK]
Common Mistakes:
Using one method with if-else for all exceptions
Handling errors in controllers, not centralized
Returning 200 OK for error responses
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.