Global Exception Handler - Input Validation

Code

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleValidationException(
            MethodArgumentNotValidException ex) {

        Map<String, String> errors = new HashMap<>();

        ex.getBindingResult()
          .getFieldErrors()
          .forEach(error ->
              errors.put(error.getField(), error.getDefaultMessage())
          );

        return ResponseEntity.badRequest().body(errors);
    }
}

What It Does

Purpose: Centralized exception handling for validation errors across all controllers

How It Works:

  1. @ControllerAdvice - Makes this class handle exceptions globally for all controllers
  2. @ExceptionHandler(MethodArgumentNotValidException.class) - Catches validation errors from @Valid annotations
  3. Extracts all field validation errors into a Map
  4. Returns HTTP 400 (Bad Request) with error details

Response Format

When validation fails, returns JSON like:

{
    "email": "Email should be valid",
    "name": "Name is required",
    "age": "Age must be greater than 0"
}

Key Components