Python: How To Handle Https Connection Refused Error And Write The Logs In Server
Solution 1:
TL;DR
If you want to avoid During handling of the above exception, another exception occurred
catch the first exception from your trace.
Your exception handling is correct it's just that you aren't catching all of them :)
In general it is okay to do that, catch exceptions which you want to handle differently otherwise just raise/handle it commonly.
Your Code:
I am getting a socket error which then raises a ConnectionError, in order to fix that add the socket error as the first exception you expect:
defGetPost(data):
logging.info('-----------GetPost Function Starts Here-----------')
try:
headers = {
'user-agent': 'customize header string',
'Content-Type': 'application/json; charset=utf-8'
}
response = requests.post('http://dummyurl.org', data= data, headers=headers, timeout=3)
logging.info('Http received response code: ', response.status_code)
response.raise_for_status()
except socket.error as exc:
logging.error(f"Caught exception socket.error : {exc}")
except requests.exceptions.HTTPError as httpErr:
logging.error("Http Error: ", exc_info=httpErr)
except requests.exceptions.ConnectionError as connErr:
logging.error("Error Connecting: ", exc_info=connErr)
except requests.exceptions.Timeout as timeOutErr:
logging.error("Timeout Error: ", exc_info=timeOutErr)
except requests.exceptions.RequestException as reqErr:
logging.error("Something Else: ", exc_info=reqErr)
except Exception as err:
raise RuntimeError(f"Something bad happened {err}") fromNone
logging.info('-----------GetPost Function Ends Here-----------')
GetPost(data)
Refer: Handling Exceptions
Solution 2:
how do define exception handling in a correct way in Python.
From your description it seems your exception handling is right.
During handling of the above exception, another exception occurred:
This problem always occur when you raise an exception or the except part has some problem in the except part.
Have you defined the 'httpErr'?
Below code seems on problem on my side:
try:
x = 2
y = 0
result = x / y
except ZeroDivisionError as e:
logging.error("Http Error: ", exc_info="<some info>")
Connection refused- what should I conclude by this error. Is it requires some credentials for the post request?? or that IP itself is not working??
There are many possible causes of this problem. Ports, firewalls, virtual networks, ip, etc. In fact, this should be considered a completely different problem, and you need to analyze it according to the specific circumstances of the things you use.
Post a Comment for "Python: How To Handle Https Connection Refused Error And Write The Logs In Server"