0
0
Spring Bootframework~5 mins

ResponseEntityExceptionHandler in Spring Boot

Choose your learning style9 modes available
Introduction

ResponseEntityExceptionHandler helps you handle errors in your Spring Boot app in one place. It makes your app send clear error messages to users.

You want to send custom error messages when something goes wrong in your app.
You want to handle common errors like 'not found' or 'bad request' without repeating code.
You want to keep your code clean by managing exceptions in one class.
You want to return HTTP status codes with error details to the client.
You want to log errors and send friendly messages instead of default server errors.
Syntax
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.

Examples
This example customizes the response when the JSON in a request is invalid.
Spring Boot
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);
    }
}
This method handles a custom exception and returns a 404 status with a message.
Spring Boot
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<Object> handleResourceNotFound(ResourceNotFoundException ex) {
    return new ResponseEntity<>("Resource not found", HttpStatus.NOT_FOUND);
}
Sample Program

This class catches validation errors and illegal argument exceptions. It sends clear messages and HTTP 400 status to the client.

Spring Boot
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);
    }
}
OutputSuccess
Important Notes

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.

Summary

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.