@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);
}
}
Purpose: Centralized exception handling for validation errors across all controllers
How It Works:
@ControllerAdvice - Makes this class handle exceptions globally for all controllers@ExceptionHandler(MethodArgumentNotValidException.class) - Catches validation errors from @Valid annotationsWhen validation fails, returns JSON like:
{
"email": "Email should be valid",
"name": "Name is required",
"age": "Age must be greater than 0"
}
@Valid validation fails@NotBlank(message = "...")))