提问人:Bob Dylan 提问时间:11/18/2015 最后编辑:Bob Dylan 更新时间:10/18/2023 访问量:20245
urllib3.exceptions.NewConnectionError 错误在一台计算机上处理,但在另一台计算机上未处理
urllib3.exceptions.NewConnectionError error handled on one machine but not on another
问:
我有一个奇怪的问题。为了获得一个简短的最小工作示例 (MWE),我们假设它返回一个对象。我们还假设我还有其他一些异常冒泡,如果在错误消息中找到,我想忽略这些异常(不是实际的单词,但嘿,这是一个 MWE)。Connect()
urllib3.connection.HTTPConnection
'magicword'
MWE:
try:
conn_obj = Connect()
except Exception as e: # there are some other exceptions I want to ignore
if 'magicword' not in e.message:
print 'fatal error: {}'.format(e.message)
这在我的机器上工作正常,并在遇到“致命错误”时打印并忽略其他异常(在这种情况下应该如此)。
但是,在同事的计算机上,错误不会得到处理,而是崩溃并创建回溯。在我的机器上这是完全相同的错误,只是他不会打印并崩溃而不是被处理。我们都使用完全相同的操作系统(Windows 7)。
显然不处理特定的异常并不理想,所以我随后尝试了该路线:
from urllib3.exceptions import NewConnectionError
try:
conn_obj = Connect()
except NewConnectionError as nce:
print 'fatal error: {}'.format(e.message)
except Exception as e: # there are some other exceptions I want to ignore
if 'magicword' not in e.message:
print 'fatal error: {}'.format(e.message)
那也行不通。由于某种原因,它不会在他的盒子上发现异常。为什么异常可以在我的机器上处理,而不是在他的机器上处理?
更新:
连接对象是在 pyelasticsearch 第三方库中引发的。我总是能够很好地捕捉到它,但它并没有在其他人的机器上使用相同的代码被捕捉到。这是我编写的一个文件,用于测试在显式引发错误时是否被捕获:
from urllib3.exceptions import NewConnectionError
def error_test(test_num):
print '\n\n'
try:
if test_num == 1:
print 'TEST 1: See if NewConnectionError is caught specifically'
raise NewConnectionError('no pool', 'test one')
elif test_num == 2:
print 'TEST 2: See if RuntimeError is caught related to magicword'
raise RuntimeError('test two magicword catching test')
elif test_num == 3:
print 'TEST 3: See if RuntimeError is caught NOT related to magicword'
raise RuntimeError('test three')
except NewConnectionError as nce:
print 'Test 1 passed successfully.\n\n{}'.format(nce.message)
except Exception as e:
if 'magicword' not in e.message:
print 'Test 3 passed successfully.\n\n{}'.format(e.message)
else:
print 'Test 2 passed successfully.\n\n{}'.format(e.message)
error_test(1)
error_test(2)
error_test(3)
该测试在我们的两台机器上都运行良好。因此,不知何故,通过让第三方库参与进来,我们的机器之间出现了不一致的东西(这实际上是在pyinstaller编译的二进制文件中,所以库差异不应该发挥作用)。
答:
0赞
Shadi
2/23/2017
#1
也许你可以试着用它来代替你的。来自 elasticsearch 的文档在这里from elasticsearch.exceptions import ConnectionError
NewConnectionError
评论
try: raise NewConnectionError('no pool', 'my magicword'); except Exception...
Exception