处理 clojure 异常的更好方法以及为什么我的异常没有在 Go Block 中捕获



我正在尝试找到一种更好的方法来处理 clojure 中的异常,我正在使用在失败时抛出 exeption 的 https://github.com/alaisi/postgres.async,但我更喜欢返回 false(因为我使用的是验证器)甚至更好的东西,例如 要么 monad(或像这样更简单的东西 http://adambard.com/blog/acceptable-error-handling-in-clojure/)

1)我正在尝试捕获异常,如果存在则返回false,但代码不起作用(不返回false并抛出异常)。

(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)如果作品返回正常,是否可以包装? 如果不起作用返回 false,或者也许 [确定? nil] 和 [nil 错误] 也许是一个宏?

----多亏了斯温,我做到了

;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?))

我不熟悉postgres.async库,但Exception不是JVM中所有异常的根源,Throwable是。

将 catch 更改为 Throwable 将是我建议的第一个更改,但似乎(<execute! ...)实际上为您捕获异常并返回它,因此您需要使用 (instance? Throwable) 检查返回值

最新更新