Enhance error handling and transaction management in item creation; explicitly commit changes and rollback on exceptions to ensure database integrity.

This commit is contained in:
mohamad 2025-05-08 22:53:26 +02:00
parent f52b47f6df
commit e484c9e9a8
2 changed files with 21 additions and 15 deletions

View File

@ -114,10 +114,10 @@ class DatabaseIntegrityError(HTTPException):
class DatabaseTransactionError(HTTPException): class DatabaseTransactionError(HTTPException):
"""Raised when a database transaction fails.""" """Raised when a database transaction fails."""
def __init__(self): def __init__(self, detail: str = settings.DB_TRANSACTION_ERROR):
super().__init__( super().__init__(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=settings.DB_TRANSACTION_ERROR detail=detail
) )
class DatabaseQueryError(HTTPException): class DatabaseQueryError(HTTPException):

View File

@ -20,7 +20,6 @@ from app.core.exceptions import (
async def create_item(db: AsyncSession, item_in: ItemCreate, list_id: int, user_id: int) -> ItemModel: async def create_item(db: AsyncSession, item_in: ItemCreate, list_id: int, user_id: int) -> ItemModel:
"""Creates a new item record for a specific list.""" """Creates a new item record for a specific list."""
try: try:
async with db.begin():
db_item = ItemModel( db_item = ItemModel(
name=item_in.name, name=item_in.name,
quantity=item_in.quantity, quantity=item_in.quantity,
@ -32,13 +31,20 @@ async def create_item(db: AsyncSession, item_in: ItemCreate, list_id: int, user_
db.add(db_item) db.add(db_item)
await db.flush() await db.flush()
await db.refresh(db_item) await db.refresh(db_item)
await db.commit() # Explicitly commit here
return db_item return db_item
except IntegrityError as e: except IntegrityError as e:
await db.rollback() # Rollback on integrity error
raise DatabaseIntegrityError(f"Failed to create item: {str(e)}") raise DatabaseIntegrityError(f"Failed to create item: {str(e)}")
except OperationalError as e: except OperationalError as e:
await db.rollback() # Rollback on operational error
raise DatabaseConnectionError(f"Database connection error: {str(e)}") raise DatabaseConnectionError(f"Database connection error: {str(e)}")
except SQLAlchemyError as e: except SQLAlchemyError as e:
await db.rollback() # Rollback on other SQLAlchemy errors
raise DatabaseTransactionError(f"Failed to create item: {str(e)}") raise DatabaseTransactionError(f"Failed to create item: {str(e)}")
except Exception as e: # Catch any other exception and attempt rollback
await db.rollback()
raise # Re-raise the original exception
async def get_items_by_list_id(db: AsyncSession, list_id: int) -> PyList[ItemModel]: async def get_items_by_list_id(db: AsyncSession, list_id: int) -> PyList[ItemModel]:
"""Gets all items belonging to a specific list, ordered by creation time.""" """Gets all items belonging to a specific list, ordered by creation time."""