package com.recipeapp.common; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.List; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity handleValidation(MethodArgumentNotValidException ex) { List details = ex.getBindingResult().getFieldErrors().stream() .map(e -> e.getField() + ": " + e.getDefaultMessage()) .toList(); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(ApiError.of("VALIDATION_ERROR", "Validation failed", details)); } @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity handleNotFound(ResourceNotFoundException ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(ApiError.of("NOT_FOUND", ex.getMessage())); } @ExceptionHandler(ConflictException.class) public ResponseEntity handleConflict(ConflictException ex) { return ResponseEntity.status(HttpStatus.CONFLICT) .body(ApiError.of("CONFLICT", ex.getMessage())); } @ExceptionHandler(ForbiddenException.class) public ResponseEntity handleForbidden(ForbiddenException ex) { return ResponseEntity.status(HttpStatus.FORBIDDEN) .body(ApiError.of("FORBIDDEN", ex.getMessage())); } @ExceptionHandler(ValidationException.class) public ResponseEntity handleBusinessValidation(ValidationException ex) { return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY) .body(ApiError.of("VALIDATION_ERROR", ex.getMessage())); } }