ResponseEntityExceptionHandler helps you handle errors in your Spring Boot app in one place. It makes your app send clear error messages to users.
ResponseEntityExceptionHandler in Spring Boot
public class MyExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleMethodArgumentNotValid( MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { // custom error response return new ResponseEntity<>("Custom error message", HttpStatus.BAD_REQUEST); } @ExceptionHandler(MyCustomException.class) public ResponseEntity<Object> handleMyCustomException(MyCustomException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } }
Extend ResponseEntityExceptionHandler to override default error handling methods.
Use @ExceptionHandler to handle specific exceptions not covered by default methods.
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleHttpMessageNotReadable( HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>("Malformed JSON request", HttpStatus.BAD_REQUEST); } }
@ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<Object> handleResourceNotFound(ResourceNotFoundException ex) { return new ResponseEntity<>("Resource not found", HttpStatus.NOT_FOUND); }
This class catches validation errors and illegal argument exceptions. It sends clear messages and HTTP 400 status to the client.
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleMethodArgumentNotValid( MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { String errorMessage = "Validation failed: " + ex.getBindingResult().getErrorCount() + " error(s)"; return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST); } @ExceptionHandler(IllegalArgumentException.class) public ResponseEntity<Object> handleIllegalArgument(IllegalArgumentException ex) { return new ResponseEntity<>("Illegal argument: " + ex.getMessage(), HttpStatus.BAD_REQUEST); } }
Use @ControllerAdvice to apply exception handling globally across controllers.
Override methods from ResponseEntityExceptionHandler to customize common Spring exceptions.
Always return meaningful messages and proper HTTP status codes for better client understanding.
ResponseEntityExceptionHandler centralizes error handling in Spring Boot apps.
Override its methods or use @ExceptionHandler for custom error responses.
This improves user experience by sending clear, consistent error messages.
Practice
ResponseEntityExceptionHandler in a Spring Boot application?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 BQuick Check:
ResponseEntityExceptionHandler centralizes REST error handling [OK]
- Confusing it with security or database management
- Thinking it configures app properties
- Assuming it handles UI rendering errors
ResponseEntityExceptionHandler to handle MethodArgumentNotValidException?Solution
Step 1: Check method signature requirements
ResponseEntityExceptionHandler requires protected method returning ResponseEntity<Object> with parameters (MethodArgumentNotValidException, HttpHeaders, HttpStatus, WebRequest).Step 2: Match options to signature
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) matches exactly. Options B and C have wrong access modifiers or parameters. protected ResponseEntity<Object> handleValidationException(Exception ex, HttpHeaders headers, HttpStatus status, WebRequest request) uses wrong exception type and method name.Final Answer:
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) -> Option DQuick Check:
Exact override signature required [OK]
- Using wrong access modifier like public or private
- Missing parameters like HttpHeaders or WebRequest
- Changing return type to something other than ResponseEntity<Object>
ResponseEntityExceptionHandler:
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
String body = "Malformed JSON request";
return new ResponseEntity<>(body, headers, HttpStatus.BAD_REQUEST);
}
What will be the HTTP status code returned when a malformed JSON is sent to the API?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 CQuick Check:
BAD_REQUEST = 400 [OK]
- Confusing BAD_REQUEST with 500 Internal Server Error
- Assuming 200 OK is returned on error
- Mixing up 404 Not Found with validation errors
@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?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 AQuick Check:
NullPointerException handled with 500 status [OK]
- Assuming validation error handler is called for NullPointerException
- Confusing 400 Bad Request with 500 Internal Server Error
- Ignoring @ExceptionHandler methods
ResponseEntityExceptionHandler methods and @ExceptionHandler to achieve this?Solution
Step 1: Understand which methods handle which exceptions
handleMethodArgumentNotValid handles validation errors; handleHttpMessageNotReadable handles JSON parse errors.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 AQuick Check:
Use overrides for validation, @ExceptionHandler for JSON errors [OK]
- Mixing exception types in wrong handlers
- Using only @ExceptionHandler without overrides
- Overriding wrong methods for given exceptions
Ready to prove it?
Pass the test and this pattern moves unknown
