Class GlobalExceptionHandler

java.lang.Object
com.example.springrest.exceptions.GlobalExceptionHandler

@RestControllerAdvice public class GlobalExceptionHandler extends Object
Global exception handler for REST controllers.

This class centralizes exception handling across the entire application. Annotated with RestControllerAdvice, it automatically intercepts exceptions thrown from @RestController methods and converts them into consistent, structured HTTP responses.

Responsibilities

  • Map exceptions to appropriate HTTP status codes.
  • Produce JSON error payloads instead of raw stack traces.
  • Improve API usability by returning descriptive, client-friendly errors.

Design notes:

  • Uses functional style with Stream and factory methods like Map.of(Object, Object) for conciseness and immutability.
  • Follows a contract of returning Map<String,String> responses, which are automatically serialized to JSON by Spring Boot.

Example error response (404):


 {
   "error": "Product not found with ID: 42"
 }
 

Example error response (400):


 {
   "name": "Name is mandatory",
   "price": "Price must be greater than 0"
 }
 
See Also:
  • Constructor Details

    • GlobalExceptionHandler

      public GlobalExceptionHandler()
  • Method Details

    • handleResourceNotFoundException

      @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(NOT_FOUND) public Map<String,String> handleResourceNotFoundException(ResourceNotFoundException ex)
      Handles ResourceNotFoundException.

      Returns an HTTP 404 (Not Found) response with a simple JSON object containing the error message.

      Old way (imperative)

      
       Map<String, String> error = new HashMap<>();
       error.put("error", ex.getMessage());
       return error;
       
      Parameters:
      ex - the exception containing the cause of the resource lookup failure
      Returns:
      a map with a single entry "error": message

      Example

      
       {
         "error": "Product not found with ID: 99"
       }
       
    • handleValidationException

      @ExceptionHandler(org.springframework.web.bind.MethodArgumentNotValidException.class) @ResponseStatus(BAD_REQUEST) public Map<String,String> handleValidationException(org.springframework.web.bind.MethodArgumentNotValidException ex)
      Handles MethodArgumentNotValidException thrown when validation of request bodies fails (e.g., @Valid DTOs).

      Builds a map where keys are the invalid field names and values are their corresponding validation error messages.

      Old way (imperative)

      
       Map<String, String> error = new HashMap<>();
       for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
           error.put(fieldError.getField(), fieldError.getDefaultMessage());
       }
       return error;
       
      Parameters:
      ex - the exception containing details of all validation errors
      Returns:
      a map of field names to validation messages

      Example

      
       {
         "name": "Name is mandatory",
         "price": "Price must be greater than 0"
       }