D · HTTPIntermediate40 min read
10. Errors, logging & CLI glue
Python · 52 pages source format
try/except specific exceptions. logging module over print. argparse for CLI tools. ruff for lint/format.
What you'll learn
- try/except/else/finally
- logging levels
- argparse basics
- ruff format
Specific exceptions
Catch FileNotFoundError, httpx.HTTPStatusError — not bare except. Re-raise when you cannot handle.
try:
resp = httpx.get(url, timeout=5.0)
resp.raise_for_status()
except httpx.TimeoutException:
logging.error("Timeout fetching %s", url)
except httpx.HTTPStatusError as e:
logging.error("HTTP %s for %s", e.response.status_code, url)Do this now
Wrap httpx call: catch timeout and HTTP errors with clear messages.
Clear?
logging over print
logging.info/warning/error with format. Control level via LOG_LEVEL env or flag.
Do this now
Replace prints in glue script with logging.
Clear?
argparse CLI
argparse.ArgumentParser for --url, --verbose. Entry point if __name__ == "__main__".
Do this now
Add CLI to health check: python -m src.health_check --file urls.txt -v
Clear?