Skip to content

Commit 98cc8db

Browse files
Harden transport fallback message extraction
Co-authored-by: Shri Sukhani <shrisukhani@users.noreply.github.com>
1 parent 4101b3d commit 98cc8db

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

hyperbrowser/transport/error_utils.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,10 +164,13 @@ def _stringify_error_value(value: Any, *, _depth: int = 0) -> str:
164164

165165
def extract_error_message(response: httpx.Response, fallback_error: Exception) -> str:
166166
def _fallback_message() -> str:
167-
response_text = response.text
167+
try:
168+
response_text = response.text
169+
except Exception:
170+
response_text = ""
168171
if isinstance(response_text, str) and response_text.strip():
169172
return _truncate_error_message(response_text)
170-
return _truncate_error_message(str(fallback_error))
173+
return _truncate_error_message(_safe_to_string(fallback_error))
171174

172175
try:
173176
error_data: Any = response.json()

tests/test_transport_error_utils.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,20 @@ def __str__(self) -> str:
148148
raise RuntimeError("cannot stringify error value")
149149

150150

151+
class _UnstringifiableFallbackError(Exception):
152+
def __str__(self) -> str:
153+
raise RuntimeError("cannot stringify fallback error")
154+
155+
156+
class _BrokenFallbackResponse:
157+
@property
158+
def text(self) -> str:
159+
raise RuntimeError("cannot read response text")
160+
161+
def json(self):
162+
raise ValueError("invalid json")
163+
164+
151165
def test_extract_request_error_context_uses_unknown_when_request_unset():
152166
method, url = extract_request_error_context(httpx.RequestError("network down"))
153167

@@ -671,6 +685,14 @@ def test_extract_error_message_uses_fallback_error_when_response_text_is_blank()
671685
assert message == "fallback detail"
672686

673687

688+
def test_extract_error_message_handles_broken_fallback_response_text():
689+
message = extract_error_message(
690+
_BrokenFallbackResponse(), _UnstringifiableFallbackError()
691+
)
692+
693+
assert message == "<unstringifiable _UnstringifiableFallbackError>"
694+
695+
674696
def test_extract_error_message_extracts_errors_list_messages():
675697
message = extract_error_message(
676698
_DummyResponse({"errors": [{"msg": "first issue"}, {"msg": "second issue"}]}),

0 commit comments

Comments
 (0)