"""Utils for httpx lib."""

import json
from contextlib import contextmanager

from httpx import HTTPStatusError


@contextmanager
def print_httpx_exception_body():
    """When httpx exceptions are raised, print the response body."""

    try:
        yield
    except HTTPStatusError as err:
        if err.response.headers.get("Content-Type") == "application/json":
            print(f"HTTP error json: {json.dumps(err.response.json(), indent=2)}")  # noqa: T201
        else:
            print(f"HTTP error json: {err.response.text}")  # noqa: T201
        raise
