retrying something 3 times before throwing an exception - in clojure

后端 未结 4 1297
旧时难觅i
旧时难觅i 2021-02-10 04:58

I don\'t know how to implement this piece of Python code in Clojure

for i in range(3):
    try:
        ......
    except e:
        if i == 2:
            raise         


        
4条回答
  •  孤独总比滥情好
    2021-02-10 05:30

    Similar to Marcyk's answer, but no macro trickery:

    (defn retry
      [retries f & args]
      (let [res (try {:value (apply f args)}
                     (catch Exception e
                       (if (zero? retries)
                         (throw e)
                         {:exception e})))]
        (if (:exception res)
          (recur (dec retries) f args)
          (:value res))))
    

    Slightly complicated because you can't recur inside a catch clause. Note that this takes a function:

    (retry 3 (fn [] 
              (println "foo") 
              (if (zero? (rand-int 2))
                  (throw (Exception. "foo"))
                  2)))
    =>
    foo ;; one or two or three of these
    foo
    2
    

提交回复
热议问题