{"record":{"id":"73e43ac9f6be8a03","repo":"psf/requests","slug":"e-73e43a","errorCode":null,"errorMessage":"{e}","messagePattern":"\\{e\\}","errorType":"exception","errorClass":"ChunkedEncodingError","httpStatus":null,"severity":"error","filePath":"src/requests/models.py","lineNumber":941,"sourceCode":"        chunk_size must be of type int or None. A value of None will\n        function differently depending on the value of `stream`.\n        stream=True will read data as it arrives in whatever size the\n        chunks are received. If stream=False, data is returned as\n        a single chunk.\n\n        If decode_unicode is True, content will be decoded using encoding\n        information from the response. If no encoding information is available,\n        bytes will be returned. This can be bypassed by manually setting\n        `encoding` on the response.\n        \"\"\"\n\n        def generate() -> Generator[bytes, None, None]:\n            # Special case for urllib3.\n            if hasattr(self.raw, \"stream\"):\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n            else:\n                # Standard file-like object.\n                while True:\n                    chunk = self.raw.read(chunk_size)\n                    if not chunk:\n                        break\n                    yield chunk\n\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()","sourceCodeStart":923,"sourceCodeEnd":959,"githubUrl":"https://github.com/psf/requests/blob/8068356288978c4f54661ae6f95afe0e0831885e/src/requests/models.py#L923-L959","documentation":"Raised inside Response.iter_content's generator when self.raw.stream() raises a urllib3.exceptions.ProtocolError — typically a malformed chunk framing, a premature connection close mid-chunk, or a violated HTTP/1.1 transfer rule. requests wraps it as ChunkedEncodingError so callers can distinguish framing failures from generic connection errors. The message is the wrapped exception's string form.","triggerScenarios":"Server sends Transfer-Encoding: chunked but closes the socket before the terminating zero-length chunk; a proxy corrupts or truncates chunk boundaries; client reads with stream=True and the upstream interrupts mid-stream.","commonSituations":"Long-lived streaming endpoints (SSE, large downloads) behind flaky proxies; reverse proxies that mis-buffer chunked responses; mobile/flaky networks that drop connections mid-transfer.","solutions":["Wrap iter_content() consumption in try/except ChunkedEncodingError and either retry the request (with Range/resume if supported) or surface a clear 'incomplete response' error.","If you control the server, ensure chunked responses always emit the terminating zero-length chunk.","Disable intermediate proxies' chunked-buffering or upgrade them; retry with a shorter timeout to fail faster."],"exampleFix":"// before\nfor chunk in resp.iter_content(8192):\n    process(chunk)\n\n// after\nfrom requests.exceptions import ChunkedEncodingError\ntry:\n    for chunk in resp.iter_content(8192):\n        process(chunk)\nexcept ChunkedEncodingError:\n    # retry or mark partial\n    ...","handlingStrategy":"try-catch","validationCode":"# Chunked framing errors cannot be reliably pre-validated client-side.\n# Configure timeouts and resume support to mitigate:\nsession.mount('https://', HTTPAdapter(max_retries=Retry(total=3)))","typeGuard":"# No client-side type guard; this is a transport-layer failure.\n# Use a Response integrity check after consumption:\ndef is_complete(resp) -> bool:\n    return resp.raw.closed and getattr(resp, '_elapsed', None) is not None","tryCatchPattern":"from requests.exceptions import ChunkedEncodingError\n\ntry:\n    for chunk in resp.iter_content(8192):\n        process(chunk)\nexcept ChunkedEncodingError as e:\n    # retry, resume (Range), or surface 'incomplete response'\n    log.warning('chunked transfer failed: %s', e)\n    raise","preventionTips":["Always wrap iter_content() consumption in try/except ChunkedEncodingError for streaming endpoints.","Configure Retry on the adapter to recover from mid-stream drops.","Use Range headers for resumable downloads of large files."],"tags":["streaming","chunkedencoding","protocolerror","network","http"],"backgroundTag":null,"analyzedSha":"8068356288978c4f54661ae6f95afe0e0831885e","analyzedAt":"2026-08-11T20:11:09.238Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}