Skip to content

Instantly share code, notes, and snippets.

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
(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)))
(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))

This comment has been minimized.

Copy link

samaaron commented Mar 20, 2011

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


This comment has been minimized.

Copy link
Owner Author

ghoseb 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.