代码之家  ›  专栏  ›  技术社区  ›  CDNthe2nd

python-异常给出了“连接中止”-我如何跳过它并继续

  •  0
  • CDNthe2nd  · 技术社区  · 7 年前

    所以基本上我使用的是请求,有时我会输入一个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
    

    我想做的是,每当这个错误再次出现时,我只想基本上“跳过”它意味着它不应该给我一个打印版,但是如果出现另一个错误,那就是 不是

    ('连接已中止',RemoteConnected('远程端关闭的连接没有响应',))
    

    然后打印错误。

    我需要做什么才能使它打印其他错误,但只需继续中断连接而不打印它?

    3 回复  |  直到 7 年前
        1
  •  2
  •   phil    7 年前

    您可以通过以下方式捕获远程断开连接的异常:

    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
    

    尽管要小心悄悄地捕获异常,但如果停止识别问题的真正原因,可能会导致以后出现问题。

        2
  •  1
  •   lenik    7 年前

    您可以尝试以下操作:

    if str(e) != 'Connection aborted.' :
        logger.error(e)
    

    但是,由于许多不同的原因,可以中止连接,并且您可能希望在 if 语句,检查 e.reason 或其他可用字段。

        3
  •  1
  •   Simas Joneliunas Kojo Clinton    7 年前

    除了远程断开之外,您应该与其他异常分开:

    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