Global Exception Handling in Spring Boot Using ResponseEntityExceptionHandler
Extending ResponseEntityExceptionHandler in Spring Boot This is one of the most important concepts in Spring Boot exception handling and is asked frequently in interviews. If you already know:โฆ
Extending ResponseEntityExceptionHandler in Spring Boot
This is one of the most important concepts in Spring Boot exception handling and is asked frequently in interviews.
If you already know:
- โ
@ExceptionHandler - โ
@ControllerAdvice - โ
@RestControllerAdvice
then this is the next topic you should learn.
What is ResponseEntityExceptionHandler?
ResponseEntityExceptionHandler is a pre-built class provided by Spring.
Instead of writing exception handlers for all Spring exceptions yourself, Spring already provides methods for handling many common exceptions.
You can simply extend this class and override the methods you want to customize.
public class ResponseEntityExceptionHandler {
...
}
Spring has already written handlers for exceptions like:
- Validation exceptions
- Missing request parameters
- Unsupported HTTP methods
- Type mismatch
- Missing request body
- Media type not supported
- etc.
Without ResponseEntityExceptionHandler
Suppose a user sends
GET /users
But your controller expects
@GetMapping
public List<User> getUsers(
@RequestParam String city) {
}
Request
GET /users
No city parameter.
Spring throws
MissingServletRequestParameterException
Without extending ResponseEntityExceptionHandler, you write
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(
MissingServletRequestParameterException.class)
public ResponseEntity<String> handle(
MissingServletRequestParameterException ex){
return ResponseEntity.badRequest()
.body(ex.getMessage());
}
}
Works perfectly.
But imagine handling 25 different Spring exceptions…
That becomes repetitive.
With ResponseEntityExceptionHandler
Simply extend it.
@RestControllerAdvice
public class GlobalExceptionHandler
extends ResponseEntityExceptionHandler {
}
Now Spring already knows how to handle many exceptions.
You only customize the response.
Example 1
Missing Request Parameter
Controller
@RestController
public class UserController {
@GetMapping("/users")
public String getUsers(
@RequestParam String city){
return city;
}
}
Request
GET /users
Output
400 Bad Request
Spring throws
MissingServletRequestParameterException
Override the handler
@RestControllerAdvice
public class GlobalExceptionHandler
extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object>
handleMissingServletRequestParameter(
MissingServletRequestParameterException ex,
HttpHeaders headers,
HttpStatusCode status,
WebRequest request) {
Map<String,Object> error =
new HashMap<>();
error.put("message",
ex.getParameterName()
+ " parameter is required");
error.put("status",400);
return new ResponseEntity<>(
error,
HttpStatus.BAD_REQUEST);
}
}
Response
{
"message":"city parameter is required",
"status":400
}
Notice:
We never wrote
@ExceptionHandler
Spring automatically called this overridden method.
Example 2
HTTP Method Not Supported
Controller
@PostMapping("/users")
public String saveUser(){
return "Saved";
}
User calls
GET /users
Spring throws
HttpRequestMethodNotSupportedException
Override
@Override
protected ResponseEntity<Object>
handleHttpRequestMethodNotSupported(
HttpRequestMethodNotSupportedException ex,
HttpHeaders headers,
HttpStatusCode status,
WebRequest request){
Map<String,Object> error =
new HashMap<>();
error.put("message",
"This API supports only "
+ ex.getSupportedHttpMethods());
error.put("status",405);
return new ResponseEntity<>(
error,
HttpStatus.METHOD_NOT_ALLOWED);
}
Output
{
"message":"This API supports only [POST]",
"status":405
}
Example 3
Validation Error
Suppose
public class UserRequest {
@NotBlank
private String name;
}
Controller
@PostMapping("/users")
public String saveUser(
@Valid
@RequestBody UserRequest request){
return "Saved";
}
Input
{
}
Spring throws
MethodArgumentNotValidException
Override
@Override
protected ResponseEntity<Object>
handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatusCode status,
WebRequest request){
Map<String,Object> errors =
new HashMap<>();
ex.getBindingResult()
.getFieldErrors()
.forEach(error ->
errors.put(
error.getField(),
error.getDefaultMessage()));
return new ResponseEntity<>(
errors,
HttpStatus.BAD_REQUEST);
}
Output
{
"name":"must not be blank"
}
This is the most commonly overridden method in Spring Boot projects.
Can We Still Use @ExceptionHandler?
Yes.
A common pattern is to combine both approaches:
@RestControllerAdvice
public class GlobalExceptionHandler
extends ResponseEntityExceptionHandler {
}
Override Spring exceptions:
@Override
protected ResponseEntity<Object>
handleMethodArgumentNotValid(...)
Handle custom exceptions with @ExceptionHandler:
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleUserNotFound(
UserNotFoundException ex){
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(ex.getMessage());
}
This combination is considered a best practice.
Which Exceptions Does It Already Handle?
ResponseEntityExceptionHandler includes handlers for many common framework exceptions, including:
| Exception | Typical HTTP Status | When it happens |
|---|---|---|
MethodArgumentNotValidException | 400 | @Valid validation fails |
MissingServletRequestParameterException | 400 | Required query parameter is missing |
HttpRequestMethodNotSupportedException | 405 | Wrong HTTP method is used |
HttpMediaTypeNotSupportedException | 415 | Unsupported Content-Type |
HttpMediaTypeNotAcceptableException | 406 | Requested response media type cannot be produced |
MissingPathVariableException | 500 (or configurable) | Required path variable is missing |
NoHandlerFoundException | 404 | No endpoint matches the request (when configured) |
AsyncRequestTimeoutException | 503 | Async request times out |
HandlerMethodValidationException (Spring 6.1+) | 400 | Method parameter validation fails |
@ExceptionHandler vs ResponseEntityExceptionHandler
| Feature | @ExceptionHandler | ResponseEntityExceptionHandler |
|---|---|---|
| Handles custom exceptions | โ Yes | โ No (use @ExceptionHandler instead) |
| Handles Spring framework exceptions | โ Yes | โ Yes |
| Built into Spring | โ No | โ Yes |
| Requires overriding methods | โ No | โ Yes |
| Best for business logic exceptions | โ Yes | โ No |
| Best for validation and request errors | โ ๏ธ Possible, but more manual | โ Yes |
Real Project Structure
A common enterprise setup looks like this:
com.example.exception
โ
โโโ GlobalExceptionHandler.java
โโโ ApiError.java
โโโ ErrorResponse.java
โโโ UserNotFoundException.java
โโโ InvalidAgeException.java
โโโ DuplicateEmailException.java
GlobalExceptionHandler.java
@RestControllerAdvice
public class GlobalExceptionHandler
extends ResponseEntityExceptionHandler {
// Override Spring exception handlers
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(...) {
// Handle validation errors
}
@Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(...) {
// Handle missing request parameters
}
// Handle custom business exceptions
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<ApiError> handleUserNotFound(UserNotFoundException ex) {
// Build and return custom error response
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiError> handleGeneral(Exception ex) {
// Fallback for unexpected exceptions
}
}
Interview Answer
What is
ResponseEntityExceptionHandler?
ResponseEntityExceptionHandler is a Spring-provided base class that contains default handlers for many common Spring MVC exceptions, such as validation failures, missing request parameters, unsupported HTTP methods, and media type errors. By extending this class in a @RestControllerAdvice, we can override only the handlers we want to customize while still benefiting from Spring’s built-in exception handling. We typically use it together with @ExceptionHandler for handling our own custom business exceptions.
Best Practice
In production Spring Boot applications:
- โ
Extend
ResponseEntityExceptionHandlerto customize responses for Spring MVC exceptions. - โ
Use
@ExceptionHandlerfor custom business exceptions (for example,UserNotFoundExceptionorDuplicateEmailException). - โ
Return a consistent error response object (for example, including
timestamp,status,error,message, andpath) for all exceptions. - โ
Keep all global exception handling logic centralized in a single
@RestControllerAdviceclass or a small set of well-organized advice classes.
This approach results in clean, maintainable, and consistent API error handling that is widely used in enterprise Spring Boot and microservices applications.