簡體   English   中英

如何捕獲原始異常

[英]How to catch the orignial exception

我正在使用帶有max_retries選項的requests模塊。 我想捕獲僅與超時和緩慢回復有關的異常:

import requests
from requests.exceptions import ConnectTimeout, Timeout

URL = 'http://exmaple.com/sleep' # sleeps for 5 seconds before reply

with requests.Session() as s:
    try:
        a = requests.adapters.HTTPAdapter(max_retries=2)
        s.mount('http://', a)
        r = s.get(URL, timeout=1)
    except (ConnectTimeout, Timeout) as err:
        print('# {} - timeout'.format(URL))

但看起來底層urllib3庫拋出ReadTimeoutError並且requests 沒有捕獲它並拋出ConnectionError

requests.exceptions.ConnectionError: HTTPConnectionPool(host='example.com', port=80): Max retries exceeded with url: /sleep (Caused by ReadTimeoutError("HTTPConnectionPool(host='example.com', port=80): Read timed out. (read timeout=1)"))

我不想將ConnectionError添加到列表中,因為還有其他繼承自它的異常,因此它也會捕獲這些異常。

有沒有辦法使用traceback模塊捕獲原始異常或鏈中的所有異常。

理想情況下,如果您希望程序拋出錯誤,您應該捕獲ConnectionError之上的其他異常並引發它們。

class OtherException(requests.exceptions.ConnectionError):
    pass

try:
    raise OtherException('This is other exception.')
except OtherException as oe:
    raise oe
except requests.exceptions.ConnectionError:
    print('The error you want to catch')

您可以使用類似的結構:

import traceback
import logging

try:
    whatever()
except Exception as e:
    logging.error(traceback.format_exc())
    # Your actions here

這幾乎可以捕獲所有內容,例如 KeyboardInterrupt 和 SystemExit。

抓住那些會使腳本很難退出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM