MongoDB 操作可能抛出哪些异常? 如何优雅的处理?

时间:2025-05-15 08:42:54
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.dao.DuplicateKeyException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.PermissionDeniedDataAccessException; // ... 其他可能的特定异常 ... import org.springframework.stereotype.Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // 假设有自定义业务异常 class MyBusinessException extends RuntimeException { private String errorCode; public MyBusinessException(String message, Throwable cause) { super(message, cause); } public MyBusinessException(String message, String errorCode, Throwable cause) { super(message, cause); this.errorCode = errorCode; } // Getter for errorCode if needed } @Service public class ProductService { private static final Logger logger = LoggerFactory.getLogger(ProductService.class); @Autowired private MongoTemplate mongoTemplate; // 或 ProductRepository /** * 插入产品 * @param product 要插入的产品 * @throws MyBusinessException 如果插入失败 */ public void addProduct(Product product) { try { mongoTemplate.insert(product, "products"); // 或者 productRepository.insert(product); } catch (DuplicateKeyException e) { logger.warn("Attempted to insert duplicate product with id: {}", product.getId(), e); // 转换为业务异常 throw new MyBusinessException("Product with this identifier or unique name already exists.", "DUPLICATE_ENTRY", e); } catch (DataAccessResourceFailureException e) { logger.error("Database resource failure during product insertion.", e); // 转换为业务异常 throw new MyBusinessException("Unable to connect to the database. Please try again later.", "DB_CONNECTION_ERROR", e); } catch (PermissionDeniedDataAccessException e) { logger.error("Permission denied during product insertion.", e); // 转换为业务异常 throw new MyBusinessException("You do not have sufficient permissions to perform this operation.", "PERMISSION_DENIED", e); } catch (DataAccessException e) { // 捕获所有其他 Spring Data Access 异常 logger.error("An unexpected database access error occurred during product insertion.", e); // 转换为通用的业务异常 throw new MyBusinessException("An unexpected database error occurred.", "DB_UNEXPECTED_ERROR", e); } catch (Exception e) { // 捕获所有其他非数据访问异常 (例如 NullPointerException, IllegalArgumentException 等) logger.error("An unexpected error occurred during product insertion.", e); throw new RuntimeException("An unexpected application error occurred.", e); } } // ... 其他方法 ... }