2015-10-31 20 views
1

如何引用記錄的函數?Clojure - 參考一個defrecord函數

對於上下文,我使用Stuart Sierra的組件。所以我有這樣的記載:

(defrecord MyComponent [] 
    component/Lifecycle 
    (start [component] 
    ...) 

    (stop [component] 
    ...) 

然而自述,它指出:

...你可以換站的身體一個try/catch,忽略所有 異常。這樣,停止一個組件的錯誤不會阻止其他組件完全關閉。

但是,我想爲此使用Dire。現在我該如何參考stop函數來使用Dire?

回答

2

有兩個自然的選擇:

  1. 你可以使用巨熊來處理錯誤的component/stop(也可能是start):

    (dire.core/with-handler! #'com.stuartsierra.component/stop 
        …) 
    

    這樣你會致力於處理錯誤的您可能在系統中使用的所有組件,以及在您的應用程序中任何地方撥打component/stop的任何呼叫。

  2. 您可以引入一個頂級函數來處理您的組件的stop邏輯,與巨熊註冊它,讓你的component/stop實現僅委託給它,也許處理start類似:

    (defn start-my-component [component] 
        …) 
    
    (defn stop-my-component [component] 
        …) 
    
    (dire.core/with-handler! #'start-my-component 
        …) 
    
    (dire.core/with-handler! #'stop-my-component 
        …) 
    
    (defrecord MyComponent […] 
        component/Lifecycle 
        (start [component] 
        (start-my-component component)) 
    
        (stop [component] 
        (stop-my-component component))) 
    
+0

那些選項聽起來不錯,但是這是否意味着沒有方法引用特定記錄中的所有'stop'方法而沒有包裝單獨的方法,是正確的? – nha

2

你不換行stop,你包裝停止的主體 - 也就是說,除了參數聲明之外的所有東西都被包裝在你的dire/with-handler!塊中,或者你喜歡的其他任何錯誤方法。無論你如何處理錯誤

(defstruct MyComponent [] 
    component/Lifecycle 
    (start [component] 
     (try (/ 1 0) 
     (catch Exception e) 
     (finally component)))) 

注意,你會破壞系統,如果你不從你start方法返回的組件。