{"record":{"id":"b3d9e60d458da1c0","repo":"unclecode/crawl4ai","slug":"failed-to-connect-str-e","errorCode":null,"errorMessage":"Failed to connect: {str(e)}","messagePattern":"Failed to connect: (.+?)","errorType":"exception","errorClass":"ConnectionError","httpStatus":null,"severity":"error","filePath":"crawl4ai/docker_client.py","lineNumber":119,"sourceCode":"\n            request_data[\"hooks\"] = {\n                \"code\": hooks_code,\n                \"timeout\": hooks_timeout\n            }\n\n        return request_data\n\n    async def _request(self, method: str, endpoint: str, **kwargs) -> httpx.Response:\n        \"\"\"Make an HTTP request with error handling.\"\"\"\n        url = urljoin(self.base_url, endpoint)\n        try:\n            response = await self._http_client.request(method, url, **kwargs)\n            response.raise_for_status()\n            return response\n        except httpx.TimeoutException as e:\n            raise ConnectionError(f\"Request timed out: {str(e)}\")\n        except httpx.RequestError as e:\n            raise ConnectionError(f\"Failed to connect: {str(e)}\")\n        except httpx.HTTPStatusError as e:\n            error_msg = (e.response.json().get(\"detail\", str(e)) \n                        if \"application/json\" in e.response.headers.get(\"content-type\", \"\") \n                        else str(e))\n            raise RequestError(f\"Server error {e.response.status_code}: {error_msg}\")\n\n    async def crawl(\n        self,\n        urls: List[str],\n        browser_config: Optional[BrowserConfig] = None,\n        crawler_config: Optional[CrawlerRunConfig] = None,\n        hooks: Optional[Union[Dict[str, Callable], Dict[str, str]]] = None,\n        hooks_timeout: int = 30\n    ) -> Union[CrawlResult, List[CrawlResult], AsyncGenerator[CrawlResult, None]]:\n        \"\"\"\n        Execute a crawl operation.\n\n        Args:","sourceCodeStart":101,"sourceCodeEnd":137,"githubUrl":"https://github.com/unclecode/crawl4ai/blob/7e801521428ee12509994d39151006f64055ebe3/crawl4ai/docker_client.py#L101-L137","documentation":"Raised by Crawl4aiDockerClient._request when the request fails with httpx.RequestError (excluding timeouts, which are handled first) — connection refused, DNS failure, TLS errors, or a reset connection. The httpx detail string is embedded in ConnectionError('Failed to connect: ...').","triggerScenarios":"Any client call made after the server container has stopped or restarted mid-session; base_url host unreachable mid-run; TLS certificate mismatch when using https; connection reset by a proxy.","commonSituations":"The Docker server exits (OOM, crash) while a batch of crawls is in flight; a laptop sleeping/restoring network mid-run; Kubernetes pod restart; the httpx client holding a pooled connection to a now-dead server.","solutions":["Re-check server health: GET {base_url}/health; restart the container if it is down","Read the embedded httpx detail: 'Connection refused' = server not listening on that port; TLS errors = certificate/scheme mismatch","Wrap calls in retry-with-reconnect logic for long-running sessions, recreating the client after server restarts","Stabilize the server (memory limits, restart policy) if it dies under load"],"exampleFix":"// before\nresults = await client.crawl(urls, ...)  # mid-session server death\n\n// after\ntry:\n    results = await client.crawl(urls, ...)\nexcept ConnectionError as e:\n    if \"Failed to connect\" in str(e):\n        await client.close()\n        client = Crawl4aiDockerClient(base_url=BASE_URL)\n        await client.authenticate(EMAIL)\n        results = await client.crawl(urls, ...)","handlingStrategy":"retry","validationCode":"import httpx\n\nasync def reachable(base_url: str) -> bool:\n    try:\n        await httpx.AsyncClient().get(f\"{base_url}/health\", timeout=5)\n        return True\n    except httpx.HTTPError:\n        return False","typeGuard":null,"tryCatchPattern":"async def crawl_resilient(make_client, **kw):\n    for i in range(3):\n        client = make_client()\n        try:\n            return await client.crawl(**kw)\n        except ConnectionError as e:\n            if \"Failed to connect\" not in str(e) or i == 2:\n                raise\n            await asyncio.sleep(2 ** i)  # server may be restarting","preventionTips":["Recreate the client after server restarts — pooled connections go stale","Run the container with a restart policy","Health-check between long-running batches"],"tags":["docker-client","network","connection-reset"],"backgroundTag":null,"analyzedSha":"7e801521428ee12509994d39151006f64055ebe3","analyzedAt":"2026-08-14T20:46:20.673Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}