From 6acc44de1629e8e6836ecd161f7587e559558afe Mon Sep 17 00:00:00 2001 From: Daulet Amirkhanov Date: Tue, 7 Oct 2025 20:14:35 +0100 Subject: [PATCH] Improve exception handling to provide clearer error context --- cognee/cli/commands/add_command.py | 6 +++--- cognee/cli/commands/cognify_command.py | 6 +++--- cognee/cli/commands/config_command.py | 16 +++++++++------- cognee/cli/commands/delete_command.py | 6 +++--- cognee/cli/commands/search_command.py | 6 +++--- .../graph/neptune_driver/neptune_utils.py | 2 +- .../relational/sqlalchemy/SqlAlchemyAdapter.py | 2 +- .../embeddings/FastembedEmbeddingEngine.py | 4 +++- .../vector/embeddings/LiteLLMEmbeddingEngine.py | 2 +- .../users/methods/get_authenticated_user.py | 4 +++- .../modules/users/roles/methods/create_role.py | 4 ++-- .../users/tenants/methods/create_tenant.py | 4 ++-- 12 files changed, 34 insertions(+), 28 deletions(-) diff --git a/cognee/cli/commands/add_command.py b/cognee/cli/commands/add_command.py index 4260b52bc..d3fea7f80 100644 --- a/cognee/cli/commands/add_command.py +++ b/cognee/cli/commands/add_command.py @@ -70,11 +70,11 @@ After adding data, use `cognee cognify` to process it into knowledge graphs. await cognee.add(data=data_to_add, dataset_name=args.dataset_name) fmt.success(f"Successfully added data to dataset '{args.dataset_name}'") except Exception as e: - raise CliCommandInnerException(f"Failed to add data: {str(e)}") + raise CliCommandInnerException(f"Failed to add data: {str(e)}") from e asyncio.run(run_add()) except Exception as e: if isinstance(e, CliCommandInnerException): - raise CliCommandException(str(e), error_code=1) - raise CliCommandException(f"Error adding data: {str(e)}", error_code=1) + raise CliCommandException(str(e), error_code=1) from e + raise CliCommandException(f"Error adding data: {str(e)}", error_code=1) from e diff --git a/cognee/cli/commands/cognify_command.py b/cognee/cli/commands/cognify_command.py index 894bfcd37..16eaf0454 100644 --- a/cognee/cli/commands/cognify_command.py +++ b/cognee/cli/commands/cognify_command.py @@ -107,7 +107,7 @@ After successful cognify processing, use `cognee search` to query the knowledge ) return result except Exception as e: - raise CliCommandInnerException(f"Failed to cognify: {str(e)}") + raise CliCommandInnerException(f"Failed to cognify: {str(e)}") from e result = asyncio.run(run_cognify()) @@ -124,5 +124,5 @@ After successful cognify processing, use `cognee search` to query the knowledge except Exception as e: if isinstance(e, CliCommandInnerException): - raise CliCommandException(str(e), error_code=1) - raise CliCommandException(f"Error during cognification: {str(e)}", error_code=1) + raise CliCommandException(str(e), error_code=1) from e + raise CliCommandException(f"Error during cognification: {str(e)}", error_code=1) from e diff --git a/cognee/cli/commands/config_command.py b/cognee/cli/commands/config_command.py index 25333e77a..752db6403 100644 --- a/cognee/cli/commands/config_command.py +++ b/cognee/cli/commands/config_command.py @@ -79,8 +79,10 @@ Configuration changes will affect how cognee processes and stores data. except Exception as e: if isinstance(e, CliCommandInnerException): - raise CliCommandException(str(e), error_code=1) - raise CliCommandException(f"Error managing configuration: {str(e)}", error_code=1) + raise CliCommandException(str(e), error_code=1) from e + raise CliCommandException( + f"Error managing configuration: {str(e)}", error_code=1 + ) from e def _handle_get(self, args: argparse.Namespace) -> None: try: @@ -122,7 +124,7 @@ Configuration changes will affect how cognee processes and stores data. fmt.note("Configuration viewing not fully implemented yet") except Exception as e: - raise CliCommandInnerException(f"Failed to get configuration: {str(e)}") + raise CliCommandInnerException(f"Failed to get configuration: {str(e)}") from e def _handle_set(self, args: argparse.Namespace) -> None: try: @@ -141,7 +143,7 @@ Configuration changes will affect how cognee processes and stores data. fmt.error(f"Failed to set configuration key '{args.key}'") except Exception as e: - raise CliCommandInnerException(f"Failed to set configuration: {str(e)}") + raise CliCommandInnerException(f"Failed to set configuration: {str(e)}") from e def _handle_unset(self, args: argparse.Namespace) -> None: try: @@ -189,7 +191,7 @@ Configuration changes will affect how cognee processes and stores data. fmt.note("Use 'cognee config list' to see all available configuration options") except Exception as e: - raise CliCommandInnerException(f"Failed to unset configuration: {str(e)}") + raise CliCommandInnerException(f"Failed to unset configuration: {str(e)}") from e def _handle_list(self, args: argparse.Namespace) -> None: try: @@ -209,7 +211,7 @@ Configuration changes will affect how cognee processes and stores data. fmt.echo(" cognee config reset - Reset all to defaults") except Exception as e: - raise CliCommandInnerException(f"Failed to list configuration: {str(e)}") + raise CliCommandInnerException(f"Failed to list configuration: {str(e)}") from e def _handle_reset(self, args: argparse.Namespace) -> None: try: @@ -222,4 +224,4 @@ Configuration changes will affect how cognee processes and stores data. fmt.echo("This would reset all settings to their default values") except Exception as e: - raise CliCommandInnerException(f"Failed to reset configuration: {str(e)}") + raise CliCommandInnerException(f"Failed to reset configuration: {str(e)}") from e diff --git a/cognee/cli/commands/delete_command.py b/cognee/cli/commands/delete_command.py index 46cf41367..8400d3b0f 100644 --- a/cognee/cli/commands/delete_command.py +++ b/cognee/cli/commands/delete_command.py @@ -100,7 +100,7 @@ Be careful with deletion operations as they are irreversible. else: await cognee.delete(dataset_name=args.dataset_name, user_id=args.user_id) except Exception as e: - raise CliCommandInnerException(f"Failed to delete: {str(e)}") + raise CliCommandInnerException(f"Failed to delete: {str(e)}") from e asyncio.run(run_delete()) # This success message may be inaccurate due to the underlying bug, but we leave it for now. @@ -108,5 +108,5 @@ Be careful with deletion operations as they are irreversible. except Exception as e: if isinstance(e, CliCommandInnerException): - raise CliCommandException(str(e), error_code=1) - raise CliCommandException(f"Error deleting data: {str(e)}", error_code=1) + raise CliCommandException(str(e), error_code=1) from e + raise CliCommandException(f"Error deleting data: {str(e)}", error_code=1) from e diff --git a/cognee/cli/commands/search_command.py b/cognee/cli/commands/search_command.py index 3540a833c..efd18591b 100644 --- a/cognee/cli/commands/search_command.py +++ b/cognee/cli/commands/search_command.py @@ -108,7 +108,7 @@ Search Types & Use Cases: ) return results except Exception as e: - raise CliCommandInnerException(f"Failed to search: {str(e)}") + raise CliCommandInnerException(f"Failed to search: {str(e)}") from e results = asyncio.run(run_search()) @@ -145,5 +145,5 @@ Search Types & Use Cases: except Exception as e: if isinstance(e, CliCommandInnerException): - raise CliCommandException(str(e), error_code=1) - raise CliCommandException(f"Error searching: {str(e)}", error_code=1) + raise CliCommandException(str(e), error_code=1) from e + raise CliCommandException(f"Error searching: {str(e)}", error_code=1) from e diff --git a/cognee/infrastructure/databases/graph/neptune_driver/neptune_utils.py b/cognee/infrastructure/databases/graph/neptune_driver/neptune_utils.py index 0f71bd4e9..e3b4c0a6a 100644 --- a/cognee/infrastructure/databases/graph/neptune_driver/neptune_utils.py +++ b/cognee/infrastructure/databases/graph/neptune_driver/neptune_utils.py @@ -53,7 +53,7 @@ def parse_neptune_url(url: str) -> Tuple[str, str]: return graph_id, region except Exception as e: - raise ValueError(f"Failed to parse Neptune Analytics URL '{url}': {str(e)}") + raise ValueError(f"Failed to parse Neptune Analytics URL '{url}': {str(e)}") from e def validate_graph_id(graph_id: str) -> bool: diff --git a/cognee/infrastructure/databases/relational/sqlalchemy/SqlAlchemyAdapter.py b/cognee/infrastructure/databases/relational/sqlalchemy/SqlAlchemyAdapter.py index 88d2abc7e..380ce9917 100644 --- a/cognee/infrastructure/databases/relational/sqlalchemy/SqlAlchemyAdapter.py +++ b/cognee/infrastructure/databases/relational/sqlalchemy/SqlAlchemyAdapter.py @@ -283,7 +283,7 @@ class SQLAlchemyAdapter: try: data_entity = (await session.scalars(select(Data).where(Data.id == data_id))).one() except (ValueError, NoResultFound) as e: - raise EntityNotFoundError(message=f"Entity not found: {str(e)}") + raise EntityNotFoundError(message=f"Entity not found: {str(e)}") from e # Check if other data objects point to the same raw data location raw_data_location_entities = ( diff --git a/cognee/infrastructure/databases/vector/embeddings/FastembedEmbeddingEngine.py b/cognee/infrastructure/databases/vector/embeddings/FastembedEmbeddingEngine.py index 8f922d934..e34ab5d9d 100644 --- a/cognee/infrastructure/databases/vector/embeddings/FastembedEmbeddingEngine.py +++ b/cognee/infrastructure/databases/vector/embeddings/FastembedEmbeddingEngine.py @@ -90,7 +90,9 @@ class FastembedEmbeddingEngine(EmbeddingEngine): except Exception as error: logger.error(f"Embedding error in FastembedEmbeddingEngine: {str(error)}") - raise EmbeddingException(f"Failed to index data points using model {self.model}") + raise EmbeddingException( + f"Failed to index data points using model {self.model}" + ) from error def get_vector_size(self) -> int: """ diff --git a/cognee/infrastructure/databases/vector/embeddings/LiteLLMEmbeddingEngine.py b/cognee/infrastructure/databases/vector/embeddings/LiteLLMEmbeddingEngine.py index d68941d25..ccef7bfcd 100644 --- a/cognee/infrastructure/databases/vector/embeddings/LiteLLMEmbeddingEngine.py +++ b/cognee/infrastructure/databases/vector/embeddings/LiteLLMEmbeddingEngine.py @@ -150,7 +150,7 @@ class LiteLLMEmbeddingEngine(EmbeddingEngine): litellm.exceptions.NotFoundError, ) as e: logger.error(f"Embedding error with model {self.model}: {str(e)}") - raise EmbeddingException(f"Failed to index data points using model {self.model}") + raise EmbeddingException(f"Failed to index data points using model {self.model}") from e except Exception as error: logger.error("Error embedding text: %s", str(error)) diff --git a/cognee/modules/users/methods/get_authenticated_user.py b/cognee/modules/users/methods/get_authenticated_user.py index a2dd2330e..d78215892 100644 --- a/cognee/modules/users/methods/get_authenticated_user.py +++ b/cognee/modules/users/methods/get_authenticated_user.py @@ -37,6 +37,8 @@ async def get_authenticated_user( except Exception as e: # Convert any get_default_user failure into a proper HTTP 500 error logger.error(f"Failed to create default user: {str(e)}") - raise HTTPException(status_code=500, detail=f"Failed to create default user: {str(e)}") + raise HTTPException( + status_code=500, detail=f"Failed to create default user: {str(e)}" + ) from e return user diff --git a/cognee/modules/users/roles/methods/create_role.py b/cognee/modules/users/roles/methods/create_role.py index a57f000fe..aa7eda91d 100644 --- a/cognee/modules/users/roles/methods/create_role.py +++ b/cognee/modules/users/roles/methods/create_role.py @@ -40,8 +40,8 @@ async def create_role( # Add association directly to the association table role = Role(name=role_name, tenant_id=tenant.id) session.add(role) - except IntegrityError: - raise EntityAlreadyExistsError(message="Role already exists for tenant.") + except IntegrityError as e: + raise EntityAlreadyExistsError(message="Role already exists for tenant.") from e await session.commit() await session.refresh(role) diff --git a/cognee/modules/users/tenants/methods/create_tenant.py b/cognee/modules/users/tenants/methods/create_tenant.py index 09dfc8855..bfd23e08f 100644 --- a/cognee/modules/users/tenants/methods/create_tenant.py +++ b/cognee/modules/users/tenants/methods/create_tenant.py @@ -35,5 +35,5 @@ async def create_tenant(tenant_name: str, user_id: UUID) -> UUID: await session.merge(user) await session.commit() return tenant.id - except IntegrityError: - raise EntityAlreadyExistsError(message="Tenant already exists.") + except IntegrityError as e: + raise EntityAlreadyExistsError(message="Tenant already exists.") from e