![](/img/trans.png)
[英]How can I skip 'Connection aborted.', OSError(0, 'Error') in Python?
[英]Python - Exception gives 'Connection aborted' - how can I skip it and continue
所以基本上我正在使用有时在其中输入URL并给我一个错误的错误请求:
('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))
当我再次执行新请求或睡眠时,这很好,现在我这样做:
except Exception as e:
logger.error(e)
randomtime = random.randint(1,5)
logger.warn('ERROR - Retrying again website %s, retrying in %d secs' % (url, randomtime))
time.sleep(randomtime)
continue
我想做的是,每当此错误再次出现为ERROR时-我只想基本地“跳过”它,这意味着它不应该给我打印出来,但是如果出现另一个不是
('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))
那么它应该打印错误。
我需要做些什么来使其打印其他错误,而只是继续以中止连接而不打印它呢?
您可以使用以下命令捕获RemoteDisconnected异常:
try:
#your code here
except requests.exceptions.ConnectionError as e:
pass
except Exception as e:
logger.error(e)
randomtime = random.randint(1,5)
logger.warn('ERROR - Retrying again website %s, retrying in %d secs' % (url, randomtime))
time.sleep(randomtime)
continue
尽管要小心地悄悄捕获异常,但是稍后可能会通过停止确定问题的真正原因而导致问题。
您可以尝试以下方法:
if str(e) != 'Connection aborted.' :
logger.error(e)
但是,由于许多不同的原因,连接可能会中止,您可能想在if
语句中添加其他检查,检查e.reason
或其他可用字段。
您应该将RemoteDisconected与其他例外分开:
from http.client import RemoteDisconnected
try:
...
except RemoteDisconnected:
continue
except Exception as e:
logger.error(e)
randomtime = random.randint(1,5)
logger.warn('ERROR - Retrying again website %s, retrying in %d secs' % (url, randomtime))
time.sleep(randomtime)
continue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.