亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Python 中實現重試時創建常規異常類

在 Python 中實現重試時創建常規異常類

汪汪一只貓 2022-08-02 11:01:20
正如標題所解釋的那樣,我想創建一個常規異常類,以從內置的異常類繼承,這些異常類稍后將在其他類中捕獲。這是我的代碼:from functools import wrapsclass ControlledException(TypeError, AttributeError):    """A generic exception on the program's domain."""class WithRetry:    def __init__(self, retries_limit=3, allowed_exceptions=None):        self.retries_limit = retries_limit        self.allowed_exceptions = allowed_exceptions or (ControlledException,)    def __call__(self, operation):        @wraps(operation)        def wrapped(*args, **kwargs):            last_raised = None            for _ in range(self.retries_limit):                try:                    return operation(*args, **kwargs)                except self.allowed_exceptions as e:                    print(f'retrying {operation.__qualname__} due to {e}')                    last_raised = e            raise last_raised        return wrapped@WithRetry()def test(x):    x = x + 1    print(x)test('a')ControlledExceptionclass 繼承了兩個異常,我想捕獲它們。在這種情況下,程序將捕獲 .TypeErrorAttributeErrorTypeError我不知道為什么這個參數對(ControlledException,)沒有影響。但是,如果我將(ControlledException,)更改為“異?!被颉邦愋湾e誤”,則會捕獲錯誤。self.allowed_exceptions
查看完整描述

1 回答

?
動漫人物

TA貢獻1815條經驗 獲得超10個贊

定義此類自定義異常時,要么必須直接使用它們,要么必須捕獲原始異常,然后引發自定義異常。raise


在這里,我捕獲了原始異常,抑制了它們的回溯并引發了自定義異常。


from functools import wraps



class ControlledException(TypeError, AttributeError):

    """A generic exception on the program's domain."""



class WithRetry:

    def __init__(self, retries_limit=3, allowed_exceptions=None):

        self.retries_limit = retries_limit

        self.allowed_exceptions = allowed_exceptions or (ControlledException,)


    def __call__(self, operation):

        @wraps(operation)

        def wrapped(*args, **kwargs):


            for _ in range(self.retries_limit):

                try:

                    return operation(*args, **kwargs)


                # if you want to catch the error, you have to catch the original

                # exceptions as opposed to custom exceptions

                except (TypeError, AttributeError) as exc:

                    print(f"retrying {operation.__qualname__} due to {exc}")


                    # this suppresses the original error message and raises your

                    # custom exception

                    raise ControlledException("Here is your error message!!") from None


        return wrapped



@WithRetry()

def test(x):

    x = x + 1

    print(x)



test("a")

這將打印出來:


retrying test due to can only concatenate str (not "int") to str

---------------------------------------------------------------------------

ControlledException                       Traceback (most recent call last)

<ipython-input-364-2a7d6eb73e92> in <module>

     38 

     39 

---> 40 test('a')


<ipython-input-364-2a7d6eb73e92> in wrapped(*args, **kwargs)

     27                     # this suppresses the original error message and raises your

     28                     # custom exception

---> 29                     raise ControlledException('Here is your error message!!') from None

     30 

     31         return wrapped


ControlledException: Here is your error message!!


查看完整回答
反對 回復 2022-08-02
  • 1 回答
  • 0 關注
  • 75 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號