2015-10-31 22 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方法返回的组件。