package com.aiteacher.config; import com.aiteacher.book.NoKnowledgeSourceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.multipart.MaxUploadSizeExceededException; import java.util.Map; import java.util.NoSuchElementException; @RestControllerAdvice public class GlobalExceptionHandler { private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(NoKnowledgeSourceException.class) public ResponseEntity> handleNoKnowledgeSource(NoKnowledgeSourceException ex) { return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) .body(Map.of("error", ex.getMessage())); } @ExceptionHandler(NoSuchElementException.class) public ResponseEntity> handleNotFound(NoSuchElementException ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(Map.of("error", ex.getMessage())); } @ExceptionHandler(IllegalArgumentException.class) public ResponseEntity> handleBadRequest(IllegalArgumentException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(Map.of("error", ex.getMessage())); } @ExceptionHandler(IllegalStateException.class) public ResponseEntity> handleConflict(IllegalStateException ex) { return ResponseEntity.status(HttpStatus.CONFLICT) .body(Map.of("error", ex.getMessage())); } @ExceptionHandler(MaxUploadSizeExceededException.class) public ResponseEntity> handleMaxUploadSize(MaxUploadSizeExceededException ex) { return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE) .body(Map.of("error", "File exceeds maximum size of 100 MB.")); } @ExceptionHandler(Exception.class) public ResponseEntity> handleGeneric(Exception ex) { log.error("Unhandled exception", ex); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(Map.of("error", "An unexpected error occurred.")); } }