Python 未捕获 Azure 模块错误处理 TCP 104

Python Azure module error handling TCP 104 not being caught

我目前正在使用 python 3.8.8 和 azure.storage.blob 的 12.9.0 版本和 azure.core 的 1.14.0 版本。

我正在使用 azure.storage.blob 包下载多个文件。我的代码如下所示

from azure.storage.blob import ContainerClient
from azure.core.exceptions import ResourceNotFoundError, AzureError
from time import sleep

max_attempts = 5
container_client = ContainerClient(DETAILS)

for file in multiple_files:

  attempts = 0

  while attempts < max_attempts:
  
    try:
    
      data = container.download_blob(file).readall()
      break
      
    except ResourceNotFoundError:
      # log missing data
      break
      
    except AzureError:
      # This is mainly here as connections seem to drop randomly.
      attempts += 1
      sleep(1)
      
  if attempts >= max_attempts:
    #log connection error
      
  #do something with the data.

似乎运行 没问题,而且我没有看到任何数据丢失。但是,在我的终端中,我不断收到消息

Unable to stream download: ("Connection broken: ConnectionResetError(104, 'Connection reset by peer')", ConnectionResetError(104, 'Connection reset by peer'))

这似乎是 TCP 104 return 消息,但 azure 模块未处理。我的问题如下。

  1. 这条消息来自哪里?我在使用的任何软件包中都看不到它。
  2. 如何更好地处理这个错误?它似乎没有被捕获为异常,因为它没有使我的代码崩溃。
  3. 我可以将其打印到日志中吗?
  1. Where is this message coming from? I can't see it in any of the packages I am using.

看起来客户端似乎已连接到服务器,但是当他们尝试传输数据时,他们收到 Errno 104 Connection reset by peer 错误。这也意味着,另一方已重置连接,否则客户端会遇到 [Errno 32] Broken pipe 异常。


  1. How do I handle this error better? It doesn't appear to be caught as an exception as it isn't crashing my code.

您可以尝试的解决方法之一是使用 try 和 catch 块来处理该异常:

from socket import error as SocketError
import errno

try:
    response = urllib2.urlopen(request).read()
except SocketError as e:
    if e.errno != errno.ECONNRESET:
        raise # Not error we are looking for
    pass # Handle error here.

也尝试参考此 similar issue,其中 sudo pip3 install urllib3 解决了问题。


  1. Can I get this to print to a log?

一种解决方法是您可以在 exc_info 参数中传递异常实例:

import logging
try:
    1/0
except Exception as e:
   logging.error('Error at %s', 'division', exc_info=e)

更多信息可以参考How to log python exception?

这是一个您可以跟进的相关问题 azure storage blob download: ConnectionResetError(104, 'Connection reset by peer')

参考: Connection broken: ConnectionResetError(104, 'Connection reset by peer') error while streaming