如何引用记录的函数?
在上下文中,我使用Stuart Sierra的组件。所以我有一个这样的记录:
(defrecord MyComponent []
component/Lifecycle
(start [component]
...)
(stop [component]
...)
然而,在自述文件中,它指出:
你可以将stop的主体包裹在一个忽略所有内容的try/catch中例外情况。这样,停止一个组件的错误不会阻止其他组件无法干净地关闭。
然而,我想使用Dire。现在,我如何引用stop
函数来与Dire一起使用?
有两个自然选项:
-
您可以使用Dire来处理
component/stop
(可能还有start
)的错误:(dire.core/with-handler! #'com.stuartsierra.component/stop …)
通过这种方式,您将致力于处理系统中可能使用的所有组件的错误,以及应用程序中任何地方对
component/stop
的任何调用。 -
您可以引入一个顶级函数来处理组件的
stop
逻辑,将其注册到Dire中,并将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)))
您不包装stop
,而是包装stop的主体——也就是说,除了参数声明之外的所有内容都包装在dire/with-handler!
块中,或者您喜欢的任何其他错误捕获方法中。
(defstruct MyComponent []
component/Lifecycle
(start [component]
(try (/ 1 0)
(catch Exception e)
(finally component))))
请注意,无论如何处理错误,如果不从start
方法返回组件,都会破坏系统。