gpt4 book ai didi

未捕获 Python 请求 ProxyError

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:29 25 4
gpt4 key购买 nike

为什么代理错误不会被第一个 except: 子句捕获?我不太明白为什么它默认为第二个子句(或者如果我删除第二个原因它只会抛出错误)

from requests.exceptions import ProxyError

try:
login(acc)
except ProxyError:
pass
except Exception as e:
print e

输出:

HTTPSConnectionPool(host='www.google.com', port=443): Max retries exceeded with url: /mail (Caused by ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 403 Forbidden',)))

最佳答案

您在这里遇到了一些边缘情况。 ProxyError 异常实际上不是 requests.exceptions 异常;它是来自嵌入式 urllib3 库的同名异常,它被包装在 MaxRetryError 异常中。

这确实是一个错误,而且确实在不久前就这样归档了,请参阅 issue #3050 .它已通过 this pull request 修复, 以引发适当的 requests.exceptions.ProxyError 异常。此修复已作为请求 2.9.2 的一部分发布。

通常,requests 会为您解包 MaxRetryError 异常,但不会针对此特定异常。如果您不能升级到 2.9.2 或更新版本,您可以专门捕获它(现在展开两层):

from requests.exceptions import ConnectionError
from requests.packages.urllib3.exceptions import MaxRetryError
from requests.packages.urllib3.exceptions import ProxyError as urllib3_ProxyError

try:
# ...
except ConnectionError as ce:
if (isinstance(ce.args[0], MaxRetryError) and
isinstance(ce.args[0].reason, urllib3_ProxyError)):
# oops, requests should have handled this, but didn't.
# see https://github.com/kennethreitz/requests/issues/3050
pass

或将拉取请求中的更改应用到您本地安装的 requests

关于未捕获 Python 请求 ProxyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36909716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com