[Python] A timeout exception is not caught as such

Discussão em 'Python' iniciado por Stack, Março 18, 2025.

  1. Stack

    Stack Membro Participativo

    I have a function that calls an API

    def somefunction():

    #....
    try:
    response = requests.post(api_url, json=payload, timeout=timeout)
    response.raise_for_status()

    result = response.json()

    # # Handle response
    # if response.status_code == 200:
    # result = response.json()
    try:
    structured_output = json.loads(result["message"]["content"])
    formatted_output = json.dumps(structured_output, indent=2)

    logger.info(json.dumps(structured_output, indent=2))
    return formatted_output
    except json.JSONDecodeError:
    logger.warning("Error parsing response:", result)
    return f"Error parsing response: {result}"

    except requests.exceptions.Timeout:
    logger.error(f"Request to {api_url} timed out after {timeout} seconds")
    raise TimeoutError(f"Request to {api_url} timed out after {timeout} seconds")

    except TimeoutError:
    logger.error(f"Low-level timeout while connecting to {api_url}")
    raise TimeoutError(f"Low-level timeout while connecting to {api_url}")

    except requests.exceptions.RequestException as e:
    # Check if the underlying exception is a TimeoutError
    if isinstance(e.__cause__, TimeoutError):
    logger.error(f"Wrapped TimeoutError detected: {e}")
    raise TimeoutError(f"Request failed due to a timeout: {e}")

    if hasattr(e, "response") and e.response is not None:
    logger.error(
    f"Request failed: {e}, Status Code: {e.response.status_code}, Response: {e.response.text}"
    )
    return f"Request failed: {e}, Status Code: {e.response.status_code}, Response: {e.response.text}"
    else:
    logger.error(f"Request failed: {e}")
    return f"Request failed: {e}"


    As you can see I ve gone to great lenghts to make sure a timeout is caught, and sometimes it is by the requests.exceptions.Timeout: part.

    somefunction:222 - Request to http://someserver:11434/api/chat timed out after 10 seconds


    however on other times I got

    somefunction:232 - Request failed: ('Connection aborted.', TimeoutError('timed out'))


    which is caught by the last else

    Why is this timeout not being caught as a timeout and how can I correct it?

    Continue reading...

Compartilhe esta Página