failjure icon indicating copy to clipboard operation
failjure copied to clipboard

Document the using with with-open

Open voldmar opened this issue 8 years ago • 2 comments

Hello!

First of all, thanks for failjure

I would be glad if you write an example how to use failjure for cases, where a user needs to close opened resources in any case. E.g. I’m doing the next:

(f/attempt-all [reader (pdf-reader source)
                document (pdf-document reader)
                fields (fields document)]
  (do
    (.close document)
    (.close reader)
    fields)
  (f/when-fail [e]
    ; Here I do not have an access to reader and document
    ; to close them
  ))

I wonder if there any mechanism to close the document and the reader in any case, like with with-open

voldmar avatar Apr 26 '17 13:04 voldmar

I made a temporary solution:

(defmacro with-f-open
  [bindings & body]
  (cond
    (= (count bindings) 0) `(do ~@body)
    (symbol? (bindings 0)) `(let ~(subvec bindings 0 2)
                              (if (f/failed? ~(bindings 0))
                                ~(bindings 0)
                                (try
                                  (with-f-open ~(subvec bindings 2) ~@body)
                                  (finally
                                    (. ~(bindings 0) close)))))

    :else (throw (IllegalArgumentException.
                   "with-f-open only allows Symbols in bindings"))))

After some reading, I think that the proper solution make some monad transformer or some magic like this

voldmar avatar May 09 '17 17:05 voldmar

Thanks for the sample! It seems to me that a monad-based solution would be the way to go, but that would probably require enough interop with algo.monads that failjure wouldn't be adding much (also, algo.monads doesn't work on clojurescript, which would be nice to have).

I'll do some experimentation sometime with cats, which is a monad library that does clojurescript too -- maybe a solution will present itself then.

adambard avatar May 09 '17 23:05 adambard