Python:如何处理 https 连接被拒绝错误并将日志写入服务器

Posted

技术标签:

【中文标题】Python:如何处理 https 连接被拒绝错误并将日志写入服务器【英文标题】:Python: How to handle https connection refused error and write the logs in server 【发布时间】:2021-09-11 01:51:03 【问题描述】:

我正在尝试处理发布请求的特定异常类型,但在执行期间 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 函数。有多个类似的帖子可用,但无法确定正确答案:(

【问题讨论】:

【参考方案1】:

TL;DR

如果您想避免 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)

参考:Handling Exceptions

【讨论】:

【参考方案2】:

如何在 Python 中以正确的方式定义异常处理。

从您的描述看来您的异常处理是正确的。

在处理上述异常的过程中,又发生了一个异常:

当你引发异常或except部分在except部分有问题时,总是会出现这个问题。

您是否定义了“httpErr”?

以下代码对我来说似乎有问题:

try: 
    x = 2
    y = 0
    result = x / y
except ZeroDivisionError as e:
    logging.error("Http Error: ", exc_info="<some info>") 

连接被拒绝-我应该对此错误得出什么结论。是吗 发布请求需要一些凭据?或者IP本身是 不工作??

这个问题有很多可能的原因。端口、防火墙、虚拟网络、ip等。其实这应该算是完全不同的问题,需要根据自己使用的东西的具体情况来分析。

【讨论】:

是的,我已经在代码中定义了except requests.exceptions.HTTPError as httpErr:..查看我的共享代码..我已经共享了我的整个函数.. 我已经更新了我的问题并分享了日志。 @Stark 对不起,我没注意到……你的代码好像没问题,让我再看看。:) 嗨,BZ,您有时间调查这个问题吗?? @Stark 你好,Stark。我昨天研究了这个,但没有找到问题的原因。对不起...

以上是关于Python:如何处理 https 连接被拒绝错误并将日志写入服务器的主要内容,如果未能解决你的问题,请参考以下文章

我可以/应该如何处理这个 git gc 错误? (rm:无法取消链接包权限被拒绝)

如何处理与 python 套接字的断开连接? (连接重置错误)

如何处理“访问被拒绝。您无权阅读活动记录”。使用服务帐户访问 Admin SDK API 时

React - 如何处理图像/文件的 403 错误 [重复]

如何处理网络请求失败错误?

vpn连接错误628,如何处理?