python-3.x - Python:如何处理 https 连接被拒绝错误并将日志写入服务器
问题描述
我正在尝试处理发布请求的特定异常类型,但在执行期间 URL 抛出错误
Connection refused
当控件到达代码时
except requests.exceptions.ConnectionError as connErr:
这本身会引发异常。 “在处理上述异常期间,发生了另一个异常:” 据我所知,打印语句不会将错误写入服务器日志,所以我必须使用记录器将日志发布到服务器。所以我的问题是:
- 如何在 Python 中以正确的方式定义异常处理。
- 连接被拒绝 - 我应该通过这个错误得出什么结论。发布请求是否需要一些凭据?还是那个IP本身不起作用?
目前我正在使用 Azure 洞察力来跟踪已发布日志中的错误。
import requests
import logging
data={'number': 12524, 'type': 'issue', 'action': 'show'}
def GetPost(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 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:
logging.error("Other error occurred: ", exc_info=err)
logging.info('-----------GetPost Function Ends Here-----------')
以下是我从 Azure Insight 获取的错误日志:
Error Connecting:
Traceback (most recent call last):
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connection.py", line 169, in _new_conn
conn = connection.create_connection(
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/util/connection.py", line 96, in create_connection
raise err
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/util/connection.py", line 86, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connectionpool.py", line 699, in urlopen
httplib_response = self._make_request(
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connectionpool.py", line 382, in _make_request
self._validate_conn(conn)
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connectionpool.py", line 1010, in _validate_conn
conn.connect()
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connection.py", line 353, in connect
conn = self._new_conn()
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connection.py", line 181, in _new_conn
raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x7f53b8c1a040>: Failed to establish a new connection: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/adapters.py", line 439, in send
resp = conn.urlopen(
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connectionpool.py", line 755, in urlopen
retries = retries.increment(
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/util/retry.py", line 574, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='dummyip', port=443): Max retries exceeded with url: /test.gateway/rest/RestEndpoint (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f53b8c1a040>: Failed to establish a new connection: [Errno 111] Connection refused'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/site/wwwroot/PWO_EventHubTrigger/postCall.py", line 13, in GetPost
response = requests.post('https://dummyip:443/test.gateway/rest/RestEndpoint', data= data, headers=headers, timeout=3)
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/api.py", line 119, in post
return request('post', url, data=data, json=json, **kwargs)
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/sessions.py", line 542, in request
resp = self.send(prep, **send_kwargs)
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/sessions.py", line 655, in send
r = adapter.send(request, **kwargs)
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='dummyip', port=443): Max retries exceeded with url: /test.gateway/rest/RestEndpoint (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f53b8c1a040>: Failed to establish a new connection: [Errno 111] Connection refused'))
我正在从主函数调用GetPost函数。我是 python 开发的新手,正在尝试编写 Azure 函数。有多个类似的帖子可用,但无法确定正确的答案:(
解决方案
TL;博士
如果您想避免During handling of the above exception, another exception occurred
从跟踪中捕获第一个异常。
您的异常处理是正确的,只是您没有捕获所有异常:)
一般来说,这样做是可以的,捕获您想要以不同方式处理的异常,否则只需通常引发/处理它。
您的代码:
我收到了一个套接字错误,然后引发了一个 ConnectionError,为了解决这个问题,将套接字错误添加为您期望的第一个异常:
def GetPost(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}") from None
logging.info('-----------GetPost Function Ends Here-----------')
GetPost(data)
参考:处理异常
推荐阅读
- python - 使用 Python 将文本文件转换为表格
- r - 计算每期有效利率的付款
- python - 如何在pygame中只允许用户在特定条件下输入?
- python - 使用python从文本中删除重复行?
- error-handling - Rust 为调试和发布模式设置了不同的恐慌输出
- tibco - TIBCO RV - 远程队列写入最大消息速率限制
- r - R:如何使用 group_by() 计算一个变量在另一个变量中的比例?
- swift - iOS 14 - 使用自定义投射对话框时未提示 LNA 权限
- multithreading - 将 ThreadPoolTaskExecutor 与 FlatFileItemReader 和 AsyncItemProcessor + Writer 一起使用是否是线程安全的?
- ios - 元组类型“()”的值没有成员“参数”[Swift]