Structured Logging & Error Boundaries
Eliminate silent bug suppression (except: pass). Implement domain-specific custom exceptions, cause chaining (raise ... from exc), JSON log formatting, and global HTTP exception handlers.
Silent Exception Suppression (except: pass) vs Cause Chaining (raise ... from exc)
Never swallow exceptions blindly with bare `except:` blocks. Catch specific domain errors, log contextual JSON data, and chain causes cleanly.
# ❌ Hides bugs, corrupts data, loses tracebacks!
try:
user = service.get_user(user_id)
except:
pass # Silent failure! System continues in invalid state.
# ✅ Logged structured warning & preserved cause
try:
user = service.get_user(user_id)
except UserNotFoundError as exc:
logger.warning("User not found: %s", user_id)
raise HTTPException(status_code=404) from exc
💻 Production Blueprint: Global Error Boundary & Structured Log
Global exception handlers catch unhandled domain errors and emit structured JSON events to logging aggregation systems.
from fastapi import Request, status
from fastapi.responses import JSONResponse
@app.exception_handler(DomainException)
async def domain_error_boundary(request: Request, exc: DomainException):
logger.error(
"Domain exception intercepted at API boundary",
extra={"path": request.url.path, "error_type": type(exc).__name__},
exc_info=True
)
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content={"error_code": "DOMAIN_RULE_VIOLATION", "message": str(exc)}
)