针对SSLCertVerificationError的正确try/except捕获方式是什么?
SSL证书验证错误的异常捕获方案
遇到的错误信息:
HTTPSConnectionPool(host='x.x.x', port=443): Max retries exceeded with url: /api/x/x/x/x (Caused by SSLError(SSLCertVerificationError("hostname 'api.exmple.com' doesn't match either of '*.azureedge.net', '*.media.microsoftstream.com', '*.origin.mediaservices.windows.net', '*.streaming.mediaservices.windows.net'")))
现有请求代码:
if 'Content-Type' in header and header['Content-Type'] == 'application/json': if username and password: response = requests.request(http_method, url, json=data, headers=header, timeout=timeout,auth=(username, password),verify=True) else: response = requests.request(http_method, url, json=data, headers=header, timeout=timeout,verify=True)
可选异常捕获方案分析
except ssl.SSLCertVerificationError:精准匹配主机名不匹配的证书验证错误,仅捕获这类特定场景,不会覆盖其他SSL错误,完全贴合当前需要处理的错误类型,适合用来触发重试。except ssl.SSLError:属于所有SSL相关错误的父类,会捕获证书验证失败、握手错误、协议错误等所有SSL层面问题。如果重试逻辑适用于所有SSL错误,可以选用,但范围比前者更广。except ssl.CertificateError:捕获所有证书相关错误,包括证书过期、无效、主机名不匹配等情况,范围介于前两者之间。若场景中可能遇到其他证书问题也需要重试,可考虑该选项。
推荐实现示例
针对当前主机名不匹配的错误,用ssl.SSLCertVerificationError做精准捕获是最优选择,示例代码如下:
import ssl import requests max_retries = 3 retry_count = 0 response = None while retry_count < max_retries: try: if 'Content-Type' in header and header['Content-Type'] == 'application/json': if username and password: response = requests.request(http_method, url, json=data, headers=header, timeout=timeout, auth=(username, password), verify=True) else: response = requests.request(http_method, url, json=data, headers=header, timeout=timeout, verify=True) break # 请求成功则退出重试循环 except ssl.SSLCertVerificationError: retry_count += 1 print(f"SSL证书验证失败,第 {retry_count} 次重试中") # 后续处理response逻辑
注意事项
- 重试次数不宜过高,避免对服务器造成不必要的压力,或陷入无限循环。
- 该错误本质是请求域名与证书绑定域名不匹配,若频繁出现,建议先检查目标域名是否正确;若业务允许,也可临时设置
verify=False跳过证书验证,但此操作会降低请求安全性,不建议在生产环境使用。
内容的提问来源于stack exchange,提问作者marwen aydi
相关产品推荐
相关产品推荐

