Im trying to catch connection error when calling http get in a Python script.
I found this post descussing the exact same issue
For me, in 99% of the calls are going smooth. but every once in a while it seems the server refuses connection, but i am not able to catch that specific error, when is happens. Other exceptions are catched.
import requests
import sys
params = {
"pair": "xbtusd",
"interval": 5
}
url = "https://api.kraken.com/0/public/OHLC"
try:
response = requests.get(url=url, params=params)
except requests.exceptions.ConnectionError as e:
print("get requests.ConnectionError: " + str(sys.exc_info()[0]) + e.args[0].reason.errno)
except requests.exceptions.RequestException as e:
print("get requests.RequestException: " + str(sys.exc_info()[0]) + e.args[0].reason.errno)
except Exception as e:
print("get general exception: " + str(sys.exc_info()[0]) + e.args[0].reason.errno)
except:
# if no connection exception is raised - catch and try again
print("get general exception2: " + str(sys.exc_info()[0]))
print(response.status_code)
if response.status_code in (200, 201, 202):
print(response.json())
This is the output when exception occur. prints i added - are not written
Traceback (most recent call last):
File "C:\Users\Oren\anaconda3\envs\v38\lib\runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\Oren\anaconda3\envs\v38\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "c:\Users\Oren\.vscode\extensions\ms-python.python-2023.4.1\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher\__main__.py", line 91, in <module>
main()
File "c:\Users\Oren\.vscode\extensions\ms-python.python-2023.4.1\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher\__main__.py", line 47, in main
launcher.connect(host, port)
File "c:\Users\Oren\.vscode\extensions\ms-python.python-2023.4.1\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher/../..\debugpy\launcher\__init__.py", line 27, in connect
sock.connect((host, port))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it