how do i catch SSL: CERTIFICATE_VERIFY_FAILED error python?

时间:2017-12-18 05:57:09

标签: python ssl exception ssl-certificate urllib3

I am using urllib3.PoolManager to make http requests. And in some part of my code I use this code to make a request

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

and I get the error SSL: CERTIFICATE_VERIFY_FAILED. Below is the full stack trace.

  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]

The error is expected. But the problem is I cannot catch the error in try except block.

I tried to use

 except ssl.SSLError:

but that does not catch this error. I also tried ssl.CertificateError but no results. I can catch it by using the Exception class but I need to catch the specific errors and handle them differently. Can someone please find me a solution to this?

2 个答案:

答案 0 :(得分:1)

I found the solution. The exception class that was being raised is urllib3.exceptions.SSLError.

答案 1 :(得分:0)

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

捕获 SSL 错误
import requests, traceback

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