Best way to handle clojure exceptions and why my exception is not being caught inside go block

I am trying to find the best way to handle exceptions in clojure, I use https://github.com/alaisi/postgres.async which threw exeption on failure, but I would rather return false (because I am using a validator) or even better that something like Either a monad (or something simpler like this http://adambard.com/blog/acceptable-error-handling-in-clojure/ )

1) I am trying to catch the exception and if there is return return false, but the code does not work (does not return false and throws an exception).

(try
      (dosql [tx (<begin! db)
                 ucount (<execute! tx ["UPDATE groups SET garticlescounter=garticlescounter + 1 WHERE gid=$1"
                                       groupid])
                 uartc (<execute! tx ["UPDATE subtopics SET starticlescount=starticlescount + 1 WHERE stid=$1"
                                      sid])
                 uartins (<insert! tx
                                   {:table "articles"}
                                   {:aurl url :atitle title :asuttopicid sid :acommentcount 0 :alikescount 0 :auid uid})
                 ok? (<commit! tx)]
                ok?)
      (catch Exception _ false))

      

2) Could it be possible to wrap in such a way that if the job returned ok? and if doesnt work, returns false, or maybe [ok? nil] and [nil error] macro possible?

---- thanks swinn I did it

;must receive an optional parameter for error response or 
; build a [nil ok] response but just know this works for me...
(defmacro async-try-block! [block]
  `(let [chn# (!/chan 1)]
     (!/go
       (let [response# (try
                        ~block
                        (catch Throwable e#))]
         (if (instance? Throwable response#) (!/put! chn# false) (!/put! chn# response#))))
     chn#))

(async-try-block!
    (dosql [tx (<begin! db)
            ucount (<execute! tx ["UPDATE groups SET garticlescounter=garticlescounter + 1 WHERE gid=$1"
                                  groupid])
            uartc (<execute! tx ["UPDATE subtopics SET starticlescount=starticlescount + 1 WHERE stid=$1"
                                 sid])
            uartins (<insert! tx
                              {:table "articles"}
                              {:aurl url :atitle title :asuttopicid sid :acommentcount 0 :alikescount 0 :auid uid})
            ok? (<commit! tx)]
           ok?))

      

+3


source to share


1 answer


I am not familiar with the postgres.async library but is Exception

not the root of all Exceptions in the JVM, Throwable

is.



Changing your catch to Throwable

would be the first change I would suggest, but it looks like it (<execute! ...)

actually gets the exception for you and returns it, so you need to check the return value with(instance? Throwable)

+2


source







All Articles