Created
March 18, 2011 14:18
-
-
Save ghoseb/876136 to your computer and use it in GitHub Desktop.
Macro to retry executing some code in case of an 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
(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)) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sam, yes, it's required. Otherwise, it won't work for functions that return nil.