Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Macro to retry executing some code in case of an exception
(ns test)
(defn try-times
"Try executing a thunk `retries` times."
[retries thunk]
(if-let [res (try
[(thunk)]
(catch Exception e ; can be any exception
(when (zero? retries)
(throw e))))]
(res 0)
(recur (dec retries) thunk)))
(defmacro with-retries
"Try executing `body`. In case of an exception, retry max `retries` times."
[retries & body]
`(try-times ~retries (fn [] ~@body)))
(comment
(defn some-io-operation
"Some read I/O operation that could throw an IOException."
[]
(println "WOULD do a read operation"))
(with-retries 10 (some-io-operation))
)
@samaaron

This comment has been minimized.

Copy link

commented Mar 20, 2011

Out of interest, why do you evaluate the thunk within a vector on line 7? Is it necessary?

@ghoseb

This comment has been minimized.

Copy link
Owner Author

commented Mar 25, 2011

Sam, yes, it's required. Otherwise, it won't work for functions that return nil.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.