Skip to content

Networking Errors and Timeouts

  • Timeouts: server too slow
  • Connection errors: server down, wrong port
  • DNS errors: domain name can’t be resolved
  • HTTP errors: 4xx/5xx responses
requests_errors.py
import requests
 
try:
    r = requests.get("https://httpbin.org/delay/10", timeout=2)
    r.raise_for_status()
    print(r.text[:100])
except requests.Timeout:
    print("Timed out")
except requests.ConnectionError:
    print("Connection error")
except requests.HTTPError as e:
    print("HTTP error:", e)
except requests.RequestException as e:
    print("Other request error:", e)
  • Always set timeout=
  • Combine with retries if needed
sketch A socket has no timeout until you give it one p5.js
The default is None, which means block forever -- a request that never returns is not a hung server so much as a missing argument. Two connections measured here, one to a closed local port and one to an unreachable address: both returned at exactly the limit that was set, 2.017 seconds for a 2 second timeout and 1.008 for a 1 second one. Worth noting what did NOT happen: the closed local port did not fail fast. On this machine the firewall drops the packet rather than refusing it, so fast failure is not something to rely on.
backoff.py
import time
import requests
 
url = "https://httpbin.org/status/503"
 
wait = 1
for attempt in range(4):
    try:
        r = requests.get(url, timeout=5)
        r.raise_for_status()
        print("success")
        break
    except requests.RequestException:
        print("failed, sleeping", wait)
        time.sleep(wait)
        wait *= 2

For production-grade retries, use a library or configure a session with retry adapters.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading