Coverage for dataexcept/database_exceptions.py: 100%
26 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 20:46 +0000
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 20:46 +0000
1"""Custom exceptions for database operations."""
3from __future__ import annotations
5from .base import DataExceptError
6from .redaction import redact_url
9class DatabaseError(DataExceptError):
10 """Base exception for database-related errors."""
12 pass
15class DatabaseConnectionError(DatabaseError):
16 """Raised when connecting to the database fails."""
18 def __init__(self, db_url: str, message: str | None = None) -> None:
19 """Initialize DatabaseConnectionError.
21 Args:
22 db_url: Database connection URL.
23 message: Optional custom error message.
24 """
25 # A connection URL routinely carries a username and password.
26 self.db_url = redact_url(db_url)
27 default = f"Failed to connect to database at '{self.db_url}'"
28 super().__init__(message or default)
31class QueryExecutionError(DatabaseError):
32 """Raised when a database query execution fails."""
34 def __init__(self, query: str, original: Exception | None = None) -> None:
35 """Initialize QueryExecutionError.
37 Args:
38 query: SQL query string.
39 original: Optional underlying exception.
40 """
41 self.query = query
42 self.original = original
43 msg = f"Query failed: {query}"
44 if original:
45 msg += f" ({original})"
46 super().__init__(msg)
49class TransactionError(DatabaseError):
50 """Raised when a database transaction fails."""
52 def __init__(
53 self,
54 transaction_id: str | None = None,
55 message: str | None = None,
56 ) -> None:
57 """Initialize TransactionError.
59 Args:
60 transaction_id: Identifier for the transaction.
61 message: Optional custom error message.
62 """
63 self.transaction_id = transaction_id
64 default = "Database transaction failed"
65 if transaction_id:
66 default += f" (id={transaction_id})"
67 super().__init__(message or default)
70__all__ = [
71 "DatabaseError",
72 "DatabaseConnectionError",
73 "QueryExecutionError",
74 "TransactionError",
75]