Skip to content

Instantly share code, notes, and snippets.

@john-kurkowski
Created August 26, 2012 23:32
Show Gist options
  • Save john-kurkowski/3484356 to your computer and use it in GitHub Desktop.
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
(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