For an IRC bot I'm writing, I want to keep trying to open a socket, even if there's an UnkownHostException
. My first thought was something like this.
(defn open-socket [{:keys [host port] :as connection}]
(try (java.net.Socket. host port)
(catch java.net.UnknownHostException _ (recur connection))))
But it doesn't work because you can't recur from a catch block. So instead I settled on something like this:
(let [socket (promise)
_ (while (not (realized? socket))
(try (deliver socket (java.net.Socket. host port))
(catch java.net.UnknownHostException _)))
socket @socket]
...
And this works, but it's awfully imperative. Is there a more functional way I could be doing this that I can't see?
Just add an or
:
(defn open-socket [{:keys [host port] :as connection}]
(or (try (java.net.Socket. host port)
(catch java.net.UnknownHostException _ nil))
(recur connection)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With