__init__.py 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. """Shared utilities for service HTTP clients."""
  2. def extract_error_text(response) -> str:
  3. """
  4. Extract a human-readable error message from an httpx Response.
  5. Priority:
  6. 1. JSON body -> 'detail' field (FastAPI / DRF standard)
  7. 2. JSON body -> 'message' field
  8. 3. JSON body -> entire dict as string
  9. 4. Raw response text (truncated to 300 chars)
  10. """
  11. try:
  12. body = response.json()
  13. if isinstance(body, dict):
  14. msg = body.get("detail") or body.get("message")
  15. if msg:
  16. # msg may itself be a list of validation errors
  17. if isinstance(msg, list):
  18. parts = []
  19. for item in msg:
  20. if isinstance(item, dict):
  21. parts.append(item.get("msg") or str(item))
  22. else:
  23. parts.append(str(item))
  24. return "; ".join(parts)
  25. return str(msg)
  26. return str(body)
  27. except Exception:
  28. pass
  29. text = response.text or ""
  30. return text[:300] if len(text) > 300 else text