crossid / accessbot

Streamline resource access grants with AI-Powered chatbot
https://www.crossid.io
Other
2 stars 0 forks source link

Optimize error handing on data layer #92

Closed asaf closed 5 months ago

asaf commented 6 months ago

Code example how to raise http error from DB integrity:

from fastapi import HTTPException
from sqlalchemy.engine.base import Connection
from sqlalchemy.exc import IntegrityError

def handle_db_operation(connection: Connection, db_operation, params):
    """
    Handles a database operation, converting SQLAlchemy IntegrityError
    to FastAPI HTTPException.

    Args:
    - connection: The SQLAlchemy connection to use for the operation.
    - db_operation: A callable representing the database operation.

    Returns:
    The result of the db_operation if successful.

    Raises:
    - HTTPException: If a unique constraint violation occurs.
    """
    try:
        # Execute the database operation
        return connection.execute(db_operation, params)
    except IntegrityError as e:
        # Check if the error is due to a unique constraint violation
        error_info = str(e.orig)
        if (
            "unique constraint" in error_info.lower()
            or "duplicate key" in error_info.lower()
        ):
            raise HTTPException(status_code=409, detail="Unique constraint violation.")
        else:
            # For other types of IntegrityErrors, you might want to handle them differently
            raise HTTPException(status_code=400, detail="Database operation failed.")
ErezSha commented 5 months ago

Duplicate of #58