2015-12-04 24 views
2

的方法我有一個具有多個函數的類。這些函數將處理類似的異常。我可以有一個處理函數並將其分配給函數。將異常處理程序分配給類

最後,我希望應該沒有在函數中的異常處理,但在異常時控制應該去這個處理函數。

Class Foo: 
    def a(): 
    try: 
     some_code 
    except Exception1 as ex: 
     log error 
     mark file for error 
     other housekeeping 
     return some_status, ex.error 
    except Exception2 as ex: 
     log error 
     mark file for error 
     other housekeeping 
     return some_status, ex.error 

同樣,其他函數也會有相同類型的異常。我想用一個單獨的方法來處理所有這些異常處理。只是函數應該把控制交給異常處理函數。

我可以考慮從包裝處理函數調用每個函數。但是這對我來說看起來很奇怪。

Class Foo: 
    def process_func(func, *args, **kwargs): 
    try: 
     func(*args, **kwargs) 
    except Exception1 as ex: 
     log error 
     mark file for error 
     other housekeeping 
     return some_status, ex.error 
    except Exception2 as ex: 
     log error 
     mark file for error 
     other housekeeping 
     return some_status, ex.error 

    def a(*args, **kwargs): 
    some_code 

有沒有更好的方法來做到這一點?

回答

3

您可以定義一個函數裝飾:

def process_func(func): 
    def wrapped_func(*args, **kwargs): 
     try: 
      func(*args, **kwargs) 
     except ... 
    return wrapped_func 

而作爲使用:

@process_func 
def func(...): 
    ... 

這樣func(...)相當於process_func(func)(...),和錯誤內wrapped_func處理。