Created
August 26, 2012 23:32
-
-
Save john-kurkowski/3484356 to your computer and use it in GitHub Desktop.
Retry on exception, returning either accumulated failures or first successful value. Based on http://stackoverflow.com/questions/1879885/clojure-how-to-to-recur-upon-exception
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn try-times-wait-millis* [times wait-millis thunk] | |
(let [attempts (repeatedly times | |
#(try (thunk) | |
(catch Exception ex (do | |
(Thread/sleep wait-millis) | |
{::failure ex})))) | |
successes (drop-while #(contains? % ::failure) attempts)] | |
(if (not (empty? successes)) | |
{:success (first successes)} | |
{:failures (map #(get % ::failure) attempts)}))) | |
(defmacro try-times-wait-millis | |
"Executes body. If an exception is thrown, will retry after wait-millis. At | |
most n tries are done. Returns union with either :success value or :failures | |
with a list of encountered exceptions." | |
[times wait-millis & thunk] | |
`(try-times-wait-millis* ~times ~wait-millis (fn [] ~@thunk))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment