I was running a small Python script one evening to draft translations of my app's store description. It had worked the day before. That night it stopped on a single line: anthropic.APIConnectionError: Connection error.
My first suspect was the API key. I regenerated it, re-exported the environment variable, and went around the same loop for about thirty minutes. The real cause was a proxy setting left behind by a VPN app I had tried that afternoon. It had nothing to do with the key.
Looking back, the reason for the detour is simple. “Connection error.” wasn't telling me anything about the cause. The answer was there the whole time — just not on the outside of the exception.
Four different failures wearing the same message
I wanted to see how much that one message hides, so I broke things on purpose. The setup was anthropic 2.11.0 on Python 3.10, on Linux.
| What I did | Exception message | Innermost exception |
|---|---|---|
| Misspelled the base_url host | Connection error. | socket.gaierror: Name or service not known |
| Pointed HTTPS_PROXY at a proxy that isn't running | Connection error. | ConnectionRefusedError: Connection refused |
| Set SSL_CERT_FILE to an unrelated CA only | Connection error. | ssl.SSLCertVerificationError: CERTIFICATE_VERIFY_FAILED |
| Set an absurdly short timeout | Request timed out or interrupted. … | TimeoutError: timed out |
The first three produced exactly the same text. The fourth reads differently, but anthropic.APITimeoutError is a subclass of APIConnectionError, so an except anthropic.APIConnectionError block catches timeouts too.
One result surprised me. In the proxy case, the innermost exception just says “Connection refused.” The word “proxy” never appears. It was my local proxy that refused the connection, yet the output reads as if api.anthropic.com had turned me away.
A script that walks down the chain
The SDK raises APIConnectionError with the lower-level exception attached as __cause__. In the version I tested, the chain was three levels deep: httpx2.ConnectError → httpcore2.ConnectError → a standard library exception. (Other SDK versions may show the name httpx instead.)
The script below follows that chain to the end and sorts the failure by the type of the innermost exception. The goal is to decide, in a single run, whether to look at the key, the network, the certificate, or the proxy.
import os
import socket
import ssl
import anthropic
PROXY_VARS = ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy")
def cause_chain(exc):
"""List the exceptions behind an APIConnectionError, outermost first."""
chain, seen = [], set()
cur = exc.__cause__ or exc.__context__
while cur is not None and id(cur) not in seen:
seen.add(id(cur))
chain.append(cur)
cur = cur.__cause__ or cur.__context__
return chain
def classify(exc):
chain = cause_chain(exc)
root = chain[-1] if chain else exc
proxy = next((os.environ[v] for v in PROXY_VARS if os.environ.get(v)), None)
if isinstance(exc, anthropic.APITimeoutError) or isinstance(root, TimeoutError):
return "timeout", "Timed out. Check the timeout value and how slow the network or VPN is."
if isinstance(root, ssl.SSLCertVerificationError):
hint = os.environ.get("SSL_CERT_FILE") or "(not set)"
return "certificate", f"Certificate verification failed. SSL_CERT_FILE={hint}; suspect an inspecting proxy."
if isinstance(root, socket.gaierror):
return "dns", "Name resolution failed. Check the base_url spelling and DNS."
if isinstance(root, ConnectionRefusedError) and proxy:
return "proxy", f"Connection refused, probably by the proxy {proxy}, not api.anthropic.com."
if isinstance(root, ConnectionRefusedError):
return "refused", "Connection refused. Check the base_url port and whether the gateway is up."
return "unknown", f"Unclassified: {type(root).__module__}.{type(root).__name__}: {root}"
def call(client):
try:
return client.messages.create(
model="claude-haiku-4-5-20251001",
max_tokens=16,
messages=[{"role": "user", "content": "ping"}],
)
except anthropic.APIConnectionError as e:
kind, hint = classify(e)
print(f"[{kind}] {type(e).__name__}: {e}")
for c in cause_chain(e):
print(f" <- {type(c).__module__}.{type(c).__name__}: {str(c)[:90]}")
print(f" => {hint}")
raise
if __name__ == "__main__":
client = anthropic.Anthropic(
api_key=os.environ.get("ANTHROPIC_API_KEY", "YOUR_API_KEY"),
base_url=os.environ.get("ANTHROPIC_BASE_URL") or None,
max_retries=0, # no retries while diagnosing, so the cause shows up on the first try
)
try:
call(client)
except anthropic.APIConnectionError:
pass
except anthropic.APIStatusError as e:
print(f"[reached] got HTTP {e.status_code}, so the connection itself works")Save it as why_connection_error.py and run it with your usual environment. Here's what it printed with the leftover proxy still set:
$ HTTPS_PROXY=http://127.0.0.1:9 python3 why_connection_error.py
[proxy] APIConnectionError: Connection error.
<- httpx2.ConnectError: [Errno 111] Connection refused
<- httpcore2.ConnectError: [Errno 111] Connection refused
<- builtins.ConnectionRefusedError: [Errno 111] Connection refused
=> Connection refused, probably by the proxy http://127.0.0.1:9, not api.anthropic.com.Three notes on why it's written this way:
max_retries=0while diagnosing. By default the SDK retries connection failures twice. On the DNS failure, no retries gave me the error in 0.0 seconds; the default setting made me wait 1.4 seconds for the same line.- Looking at the last link. Every
ConnectErrorin the middle has the same type. The only distinguishing detail lives in the standard library exception at the bottom. - Getting a 401 on purpose. Even with a placeholder key,
[reached] HTTP 401means the connection works. That's the moment you can separate a key problem from a network problem.
How I fix each of the four
Once the failure is sorted, each fix is short. This is the order I work in.
dns
Check the host name in ANTHROPIC_BASE_URL and whether your DNS can resolve external domains. If python3 -c "import socket; print(socket.getaddrinfo('api.anthropic.com', 443)[0][4])" returns an IP address, DNS is fine and the problem is in your base_url.
proxy
Run env | grep -i proxy and look for values you don't remember setting — that was my case. If you don't need a proxy, unset the variable. If you do, exclude only the API with NO_PROXY=api.anthropic.com. In my test, keeping the broken proxy but adding NO_PROXY brought back the 401 immediately.
certificate
On networks where a corporate device decrypts and inspects traffic, Python has to trust that device's CA. The reliable approach is to build a bundle with the device's CA plus the standard ones and pass it through SSL_CERT_FILE.
One trap here: when I pointed SSL_CERT_FILE at an empty file, the failure came when the client was constructed, not when the request was sent, and it was an ssl.SSLError, not an APIConnectionError. The except in the script above won't catch it. I'd resist reaching for verify=False; check what's actually in the file you're passing instead.
timeout
The defaults I saw were 5 seconds to connect and 600 seconds to read. If it fails while connecting, look at the network or VPN. If it fails partway through a response, rethink how you handle long outputs. A long response timing out while automatic retries kick in can quietly bill you twice; I wrote up how that happens, and how I redesigned around it, in Long non-streaming responses were silently billed twice at the 10-minute wall.
One field to keep in production logs
The diagnostic script is enough on your own machine, but I now leave just the cause label in production logs too. It's one extra field in the except of the function that wraps each request:
import logging
import anthropic
from why_connection_error import classify
logger = logging.getLogger("claude")
def send(client, **params):
try:
return client.messages.create(**params)
except anthropic.APIConnectionError as e:
kind, _ = classify(e)
logger.warning("claude_connection_error", extra={"kind": kind, "retries": client.max_retries})
raiseWith that in place, the next morning I can count “three dns, one timeout.” Before, I'd stare at a column of identical “Connection error.” lines with no way to tell which ones shared a cause.
Judge by the innermost line, not the exception's name. As an indie developer running these scripts alone, I only raise the retry count once I know the cause is a timeout. Retry design itself is a separate topic; I covered it in What the Anthropic SDK did with a 120-second retry-after.
If it still doesn't work
If none of the four match and you get unknown, run curl -sv https://api.anthropic.com/v1/messages -o /dev/null once from the same machine and see where the TLS handshake stops. If curl gets through but Python fails, you've narrowed it down to differences in the certificates and environment variables Python is reading.
If you're still stuck, paste the [unknown] line as-is when you ask your gateway admin or network team. “The innermost exception is X” gets people moving much faster than “I'm getting Connection error.”
Tonight, while nothing is broken, try running why_connection_error.py once with your usual environment and confirm you see [reached]. Doing it once on a calm evening saves a lot of guessing on the night something does stop.