Skip to content

Fix: retain stream read error on subsequent response.content access#7415

Open
hellozzm wants to merge 1 commit intopsf:mainfrom
hellozzm:fix-response-content-error-retention
Open

Fix: retain stream read error on subsequent response.content access#7415
hellozzm wants to merge 1 commit intopsf:mainfrom
hellozzm:fix-response-content-error-retention

Conversation

@hellozzm
Copy link
Copy Markdown

@hellozzm hellozzm commented May 6, 2026

Summary

Fixes #4965

When accessing response.content raises an exception during stream reading (e.g., ConnectionError), subsequent accesses would silently return an empty bytestring b"" instead of re-raising the original error.

This made debugging difficult, especially in debuggers where properties may be accessed multiple times.

Changes

  • Store the exception in _content_error when iter_content raises during content reading
  • On subsequent accesses, re-raise the stored exception

Testing

from unittest.mock import MagicMock
from requests.models import Response

r = Response()
r.status_code = 200
r.raw = MagicMock()
r.raw.stream = MagicMock(side_effect=ConnectionError('reset'))

try:
    _ = r.content
except ConnectionError:
    print('First: raised')  # ✓

try:
    _ = r.content
except ConnectionError:
    print('Second: raised')  # ✓ (previously returned b'')

When accessing response.content raises an exception during stream reading,
subsequent accesses would silently return an empty bytestring instead of
re-raising the original error. This made debugging difficult, especially
in debuggers where properties may be accessed multiple times.

The fix stores the exception and re-raises it on subsequent accesses.

Fixes psf#4965
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Accessing response.content twice removes forgets read error

1 participant