Debug Exception Chaining & Suppressed Context
Catching an internal failure and re-raising a custom exception by default prints both tracebacks, leaking database credentials or API secrets. Using raise NewException() from None suppresses __context__, delivering clean, secure error outputs.
try:
connect_db("postgres://secret_pw@host/db")
except ConnectionError:
# Suppress internal context to prevent secret leakage
raise ServiceUnavailableError("DB unreachable") from None
# Debug Exception Chaining & Suppressed Context When an internal database query fails with `ConnectionRefusedError: failed to connect to postgres://admin:super_secret_pw@db.internal:5432/core`, wrapping it with `raise ClientFacingError("Database failed")` still displays: 🛑🔒 ```text During handling of the above exception, another exception occurred: ... ``` That leaked your raw database URI and password straight into your customer's browser or public logging aggregator! Python’s `from None` construct explicitly severs the exception chain, guaranteeing that internal secrets stay buried. ```python try: risky_internal_call() except LowLevelError: raise CleanPublicError("Operation failed") from None ``` ## Pop Quiz What does the syntax `raise CustomError(...) from None` explicitly do in Python 3? - [ ] It suppresses the __context__ attribute, preventing the original exception traceback from being displayed. - [ ] It converts the raised exception into an asynchronous CoroutineExit warning. - [ ] It instructs the garbage collector to immediately purge the exception frame from heap memory. - [ ] It disables traceback generation across all threads in the active process. ## Real-World Challenge Implement `safe_database_query(conn_uri: str)`. When a connection fails, catch the error and raise a custom `SanitizedDatabaseError("Database cluster unreachable") from None`. Verify that neither credentials nor the original exception context leak on the raised exception. <details> <summary>Solution</summary> ```python class SanitizedDatabaseError(Exception): pass def safe_database_query(conn_uri: str): try: # Simulate connection failure with sensitive URI raise ConnectionRefusedError(f"Connection failed for URI: {conn_uri}") except ConnectionRefusedError: raise SanitizedDatabaseError("Database cluster unreachable") from None # Verification caught = False try: safe_database_query("postgres://admin:SuperSecretToken123@10.0.4.12:5432/users") except SanitizedDatabaseError as err: caught = True assert "SuperSecretToken123" not in str(err) assert err.__cause__ is None assert err.__suppress_context__ is True assert caught is True ``` </details>