Manuals / Python / Chapter 10

D · HTTP · intermediate · Week 5 · Chapter 10 of 13

Errors, logging & CLI glue

try/except specific exceptions. logging module over print. argparse for CLI tools. ruff for lint/format.

Path progress
72%

Step 1 of 3

Specific exceptions

Catch FileNotFoundError, httpx.HTTPStatusError — not bare except. Re-raise when you cannot handle.

Specific exceptionsDrag stickies · tap for tips
Study mapDrag stickies · tap for tipsKeep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Assert the UIdrag · tap →Retry wiselydrag · tap →Seed datadrag · tap →Close the loopdrag · tap →Keep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Pathwise hackdrag · tap →Specific exceptiondrag · tap →Try thisdrag · tap →Follow the dashed drag · tap →

Example

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.

Was this step clear?
Chapter learning outcomes
  • try/except/else/finally
  • logging levels
  • argparse basics
  • ruff format

Clear these before you leave

Side quest

Retry wrapper

retry(fn, attempts=3, delay=1) with logging on failure.