Skip to content

Instantly share code, notes, and snippets.

@ghoseb
Created March 18, 2011 14:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghoseb/876136 to your computer and use it in GitHub Desktop.
Save ghoseb/876136 to your computer and use it in GitHub Desktop.
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
Copy link

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

@ghoseb
Copy link
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