Skip to content

Commit b313841

Browse files
Bound HyperbrowserError message rendering length
Co-authored-by: Shri Sukhani <shrisukhani@users.noreply.github.com>
1 parent 4612080 commit b313841

2 files changed

Lines changed: 31 additions & 1 deletion

File tree

hyperbrowser/exceptions.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,20 @@
11
# exceptions.py
22
from typing import Optional, Any
33

4+
_MAX_EXCEPTION_DISPLAY_LENGTH = 2000
5+
_TRUNCATED_EXCEPTION_DISPLAY_SUFFIX = "... (truncated)"
6+
7+
8+
def _truncate_exception_text(text_value: str) -> str:
9+
if len(text_value) <= _MAX_EXCEPTION_DISPLAY_LENGTH:
10+
return text_value
11+
available_length = _MAX_EXCEPTION_DISPLAY_LENGTH - len(
12+
_TRUNCATED_EXCEPTION_DISPLAY_SUFFIX
13+
)
14+
if available_length <= 0:
15+
return _TRUNCATED_EXCEPTION_DISPLAY_SUFFIX
16+
return f"{text_value[:available_length]}{_TRUNCATED_EXCEPTION_DISPLAY_SUFFIX}"
17+
418

519
def _safe_exception_text(value: Any, *, fallback: str) -> str:
620
try:
@@ -12,7 +26,7 @@ def _safe_exception_text(value: Any, *, fallback: str) -> str:
1226
for character in text_value
1327
)
1428
if sanitized_value.strip():
15-
return sanitized_value
29+
return _truncate_exception_text(sanitized_value)
1630
return fallback
1731

1832

tests/test_exceptions.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,19 @@ def test_hyperbrowser_error_str_uses_placeholder_for_blank_message():
3737
error = HyperbrowserError(" ")
3838

3939
assert str(error) == "Hyperbrowser error"
40+
41+
42+
def test_hyperbrowser_error_str_truncates_oversized_message():
43+
error = HyperbrowserError("x" * 2500)
44+
45+
assert str(error).endswith("... (truncated)")
46+
assert len(str(error)) <= 2000
47+
48+
49+
def test_hyperbrowser_error_str_truncates_oversized_original_error_message():
50+
root_cause = ValueError("y" * 2500)
51+
error = HyperbrowserError("request failed", original_error=root_cause)
52+
53+
rendered_error = str(error)
54+
assert "Caused by ValueError:" in rendered_error
55+
assert rendered_error.endswith("... (truncated)")

0 commit comments

Comments
 (0)