Handling Errors Gracefully with ResponseEntityExceptionHandler in Spring Boot
📖 Scenario: You are building a simple Spring Boot REST API for a bookstore. You want to handle errors like when a book is not found or when invalid data is sent by the user. Instead of showing raw error messages, you want to send clear, friendly error responses.
🎯 Goal: Create a custom exception handler by extending ResponseEntityExceptionHandler to catch specific exceptions and return meaningful HTTP responses with error messages.
📋 What You'll Learn
Create a custom exception class called BookNotFoundException.
Create a controller class BookController with a method to get a book by ID.
Create a class CustomExceptionHandler that extends ResponseEntityExceptionHandler.
Override the method to handle BookNotFoundException and return a ResponseEntity with status 404 and a custom error message.
💡 Why This Matters
🌍 Real World
In real applications, handling exceptions gracefully improves user experience by sending clear error messages instead of server errors or stack traces.
💼 Career
Knowing how to customize error handling with ResponseEntityExceptionHandler is a key skill for backend developers working with Spring Boot REST APIs.
Progress0 / 4 steps
1
Create the custom exception class
Create a public class called BookNotFoundException that extends RuntimeException. Add a constructor that accepts a String message and passes it to the superclass constructor.
Spring Boot
Hint
Think of this as creating a special kind of error that you can throw when a book is not found.
2
Create the BookController with a method to get a book by ID
Create a class called BookController annotated with @RestController. Add a method getBookById that takes a Long id parameter annotated with @PathVariable. Inside the method, throw a BookNotFoundException with the message "Book not found with id " + id.
Spring Boot
Hint
This simulates a request for a book that always fails by throwing your custom exception.
3
Create the CustomExceptionHandler class extending ResponseEntityExceptionHandler
Create a class called CustomExceptionHandler annotated with @ControllerAdvice that extends ResponseEntityExceptionHandler. Add a method handleBookNotFoundException annotated with @ExceptionHandler(BookNotFoundException.class) that takes a BookNotFoundException ex parameter. Return a ResponseEntity with status HttpStatus.NOT_FOUND and body containing ex.getMessage().
Spring Boot
Hint
This class catches your custom exception and sends a 404 response with the error message.
4
Complete the exception handler with a fallback for other exceptions
In the CustomExceptionHandler class, add a method handleAllExceptions annotated with @ExceptionHandler(Exception.class) that takes an Exception ex parameter. Return a ResponseEntity with status HttpStatus.INTERNAL_SERVER_ERROR and body "An unexpected error occurred".
Spring Boot
Hint
This fallback method catches any other errors and sends a 500 response with a friendly message.
Practice
(1/5)
1. What is the main purpose of ResponseEntityExceptionHandler in a Spring Boot application?
easy
A. To handle user authentication and authorization
B. To centralize and customize error handling for REST controllers
C. To manage database connections automatically
D. To configure application properties at runtime
Solution
Step 1: Understand the role of ResponseEntityExceptionHandler
This class provides a centralized way to handle exceptions thrown by REST controllers in Spring Boot.
Step 2: Compare with other options
Options A, B, and D relate to authentication, database management, and configuration, which are not the responsibility of ResponseEntityExceptionHandler.
Final Answer:
To centralize and customize error handling for REST controllers -> Option B
What will be the HTTP status code returned when a malformed JSON is sent to the API?
medium
A. 200 OK
B. 500 Internal Server Error
C. 400 Bad Request
D. 404 Not Found
Solution
Step 1: Analyze the overridden method
The method returns a ResponseEntity with status HttpStatus.BAD_REQUEST when JSON is malformed.
Step 2: Identify the HTTP status code for BAD_REQUEST
BAD_REQUEST corresponds to HTTP status code 400.
Final Answer:
400 Bad Request -> Option C
Quick Check:
BAD_REQUEST = 400 [OK]
Hint: BAD_REQUEST means 400 status code [OK]
Common Mistakes:
Confusing BAD_REQUEST with 500 Internal Server Error
Assuming 200 OK is returned on error
Mixing up 404 Not Found with validation errors
4. Consider this custom exception handler class:
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<Object> handleNullPointer(NullPointerException ex, WebRequest request) {
String body = "Null value found";
return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
String body = "Validation failed";
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
}
If a NullPointerException occurs, what will be the HTTP status code returned?
medium
A. 500 Internal Server Error
B. 400 Bad Request
C. 404 Not Found
D. 200 OK
Solution
Step 1: Identify the handler for NullPointerException
The method annotated with @ExceptionHandler(NullPointerException.class) returns status INTERNAL_SERVER_ERROR.
Step 2: Map INTERNAL_SERVER_ERROR to HTTP status code
INTERNAL_SERVER_ERROR corresponds to HTTP status 500.
Final Answer:
500 Internal Server Error -> Option A
Quick Check:
NullPointerException handled with 500 status [OK]
Hint: Check @ExceptionHandler annotation for exception type [OK]
Common Mistakes:
Assuming validation error handler is called for NullPointerException
Confusing 400 Bad Request with 500 Internal Server Error
Ignoring @ExceptionHandler methods
5. You want to customize error responses for both validation errors and JSON parse errors in your Spring Boot REST API. Which approach correctly combines ResponseEntityExceptionHandler methods and @ExceptionHandler to achieve this?
hard
A. Override handleMethodArgumentNotValid for validation errors and add an @ExceptionHandler for HttpMessageNotReadableException
B. Use only @ExceptionHandler methods for all exceptions, no overrides needed
C. Override handleHttpMessageNotReadable for validation errors and use @ExceptionHandler for MethodArgumentNotValidException
D. Override handleExceptionInternal to catch all exceptions globally
Solution
Step 1: Understand which methods handle which exceptions
Step 2: Combine overrides and @ExceptionHandler correctly
Override handleMethodArgumentNotValid for validation errors and use @ExceptionHandler for HttpMessageNotReadableException to customize JSON parse error responses.
Final Answer:
Override handleMethodArgumentNotValid for validation errors and add an @ExceptionHandler for HttpMessageNotReadableException -> Option A
Quick Check:
Use overrides for validation, @ExceptionHandler for JSON errors [OK]
Hint: Override validation method, @ExceptionHandler for JSON parse errors [OK]
Common Mistakes:
Mixing exception types in wrong handlers
Using only @ExceptionHandler without overrides
Overriding wrong methods for given exceptions
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.