1
0

util.error_text_str_to_safe_str: truncate long errors

The messages are sometimes logged and sometimes shown to the user,
- for logging we might not want to truncate or have higher limits,
- but when shown to the user, we definitely want to truncate the error text.
It is simplest to just do the truncation here, at the lowest level.

Note that we usually prepend the error text with a header e.g. "[DO NOT TRUST THIS MESSAGE]"
and if the error text is too long, this header at the beginning might get "lost" in some way.
Hence we should truncate the error text.
This commit is contained in:
SomberNight
2024-06-17 16:24:27 +00:00
parent 09e0413d38
commit bec78b4210
3 changed files with 26 additions and 7 deletions

View File

@@ -2087,14 +2087,17 @@ def get_running_loop() -> Optional[asyncio.AbstractEventLoop]:
return None
def error_text_str_to_safe_str(err: str) -> str:
def error_text_str_to_safe_str(err: str, *, max_len: Optional[int] = 500) -> str:
"""Converts an untrusted error string to a sane printable ascii str.
Never raises.
"""
return error_text_bytes_to_safe_str(err.encode("ascii", errors='backslashreplace'))
text = error_text_bytes_to_safe_str(
err.encode("ascii", errors='backslashreplace'),
max_len=None)
return truncate_text(text, max_len=max_len)
def error_text_bytes_to_safe_str(err: bytes) -> str:
def error_text_bytes_to_safe_str(err: bytes, *, max_len: Optional[int] = 500) -> str:
"""Converts an untrusted error bytes text to a sane printable ascii str.
Never raises.
@@ -2107,4 +2110,12 @@ def error_text_bytes_to_safe_str(err: bytes) -> str:
# convert to ascii, to get rid of unicode stuff
ascii_text = err.decode("ascii", errors='backslashreplace')
# do repr to handle ascii special chars (especially when printing/logging the str)
return repr(ascii_text)
text = repr(ascii_text)
return truncate_text(text, max_len=max_len)
def truncate_text(text: str, *, max_len: Optional[int]) -> str:
if max_len is None or len(text) <= max_len:
return text
else:
return text[:max_len] + f"... (truncated. orig_len={len(text)})"