File size: 1,391 Bytes
824f29f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import httpx
def clean_error_message(e: Exception, action: str) -> str:
"""
Produce a short, actionable status message for a failed API call.
Never surfaces raw exception/HTTP text (stack traces, MDN links, etc.)
to end users — those are confusing and unprofessional in a live demo.
"""
if isinstance(e, httpx.HTTPStatusError):
status = e.response.status_code
if status == 500:
return (
f"{action} failed — the server hit an internal error. This is often caused by "
"a source text too large for the model's context window, or a temporary resource "
"issue. Try a smaller token count or try again in a moment."
)
if status in (502, 503, 504):
return f"{action} failed — the server is temporarily unavailable (HTTP {status}). Try again in a moment."
return f"{action} failed — the server returned an error (HTTP {status})."
if isinstance(e, (httpx.ConnectError, httpx.ConnectTimeout)):
return f"{action} failed — could not connect to the service. It may be waking up from sleep; try again shortly."
if isinstance(e, (httpx.ReadTimeout, httpx.TimeoutException)):
return f"{action} failed — the request timed out. Try a smaller request, or try again."
return f"{action} failed — an unexpected error occurred."
|