Code philosophy

Exceptions over failure indicators

13 October 2026 · 5 min read

The Danger of Silent Failures

Consider a pattern that appears in countless production codebases:

async def find_user(user_id: int) -> User | None:
    try:
        return await db.fetch_user(user_id)
    except DatabaseConnectionError:
        return None  # The failure silently disguised as "Not Found"

The issue isn’t returning None per se—the catastrophe is that None is completely ambiguous.

Does None mean the user truly does not exist in the database? Or does it mean the database connection timed out? Or that the query syntax was malformed? Or that authentication expired?

When the caller receives None, it is forced to make a guess:

user = await find_user(user_id)
if not user:
    # Danger: Informs the client that the account does not exist,
    # even though the database server was simply rebooting!
    return Response(status_code=404, detail="User not found")

This code “succeeds” silently in production while compounding damage. Silent returns push the location of the error far away from where it originated, turning trivial diagnostics into multi-day investigations.


The Core Philosophy: Fail Loudly, Fail Specifically

Errors should never pass silently unless explicitly silenced. High-reliability systems rely on strongly typed, domain-specific exception hierarchies:

class DomainError(Exception):
    """Base exception for all business domain errors."""

class UserNotFoundError(DomainError):
    def __init__(self, user_id: int):
        super().__init__(f"User with identifier {user_id} was not found.")
        self.user_id = user_id

class UserSuspendedError(DomainError):
    def __init__(self, user_id: int, reason: str):
        super().__init__(f"User {user_id} is currently suspended: {reason}")
        self.user_id = user_id
        self.reason = reason

Now, the service boundary communicates with absolute fidelity:

async def find_user(user_id: int) -> User:
    user = await db.fetch_user(user_id)
    if not user:
        raise UserNotFoundError(user_id)
    if user.is_suspended:
        raise UserSuspendedError(user_id, user.suspension_reason)
    return user

Centralized Exception Mapping

By throwing explicit domain exceptions, the transport layer (FastAPI router, gRPC handler, CLI command) can map errors deterministically into human-friendly responses via a centralized exception handler:

@app.exception_handler(UserNotFoundError)
async def user_not_found_handler(request: Request, exc: UserNotFoundError):
    return JSONResponse(
        status_code=404,
        content={"error": "not_found", "message": str(exc), "resource_id": exc.user_id},
    )

@app.exception_handler(UserSuspendedError)
async def user_suspended_handler(request: Request, exc: UserSuspendedError):
    return JSONResponse(
        status_code=403,
        content={"error": "account_suspended", "reason": exc.reason},
    )

Key Engineering Benefits:

  • No More Inferred Failures: Callers never guess why an operation failed.
  • Self-Documenting API Contracts: Domain exceptions clearly describe failure states directly in code.
  • Accurate Telemetry and Alerting: 500-level infrastructure outages (network partitions, disk failures) are never masked as 404 client errors.