我如何捕获 SSL:CERTIFICATE_VERIFY_FAILED 错误 python?

how do i catch SSL: CERTIFICATE_VERIFY_FAILED error python?

我正在使用 urllib3.PoolManager 发出 http 请求。在我的代码的某些部分中,我使用此代码发出请求

resp = h.request(self.method, self.url, body=body, headers=headers, timeout=TIMEOUT, retries=retries)

我收到错误 SSL:CERTIFICATE_VERIFY_FAILED。下面是完整的堆栈跟踪。

  File "/lib/python2.7/site-packages/urllib3/request.py", line 69, in request
    **urlopen_kw)

  File "/lib/python2.7/site-packages/urllib3/request.py", line 90, in request_encode_url
    return self.urlopen(method, url, **extra_kw)

  File "/lib/python2.7/site-packages/urllib3/poolmanager.py", line 248, in urlopen
    response = conn.urlopen(method, u.request_uri, **kw)

  File "/lib/python2.7/site-packages/urllib3/connectionpool.py", line 621, in urlopen
    raise SSLError(e)

[SSL: CERTIFICATE_VERIFY_FAILED]

错误在意料之中。但问题是我无法捕获 try except block 中的错误。

我尝试使用

 except ssl.SSLError:

但这并没有捕捉到这个错误。 我也试过 ssl.CertificateError 但没有结果。 我可以使用 Exception class 捕获它,但我需要捕获特定错误并以不同方式处理它们。有人可以帮我解决这个问题吗?

我找到了解决方案。引发的异常 class 是 urllib3.exceptions.SSLError.

迟到的答案,但您可以使用 requests.exceptions.SSLError

捕获 SSL 错误
import requests, traceback

try:
    r = requests.get('https://domain.tld')
except (requests.exceptions.SSLError):
    print(traceback.format_exc())

要查找任何异常的具体类型,您可以使用type()

import requests

try:
    r = requests.get('https://domain.tld')
except Exception as e:
    print(type(e))

输出:

<class 'requests.exceptions.ConnectionError'>

这导致我们:

import requests

try:
    r = requests.get('https://domain.tld')
except requests.exceptions.ConnectionError as e:
    print("Caught correctly")

输出:

Caught correctly