我想存储一系列验证错误,然后将错误打印到控制台。我怎样才能做到最好?我尝试使用下面的代码,但err
似乎总是设置为[]。
(defn foo-bar [doc]
(let [err []]
(if (= (get doc "foo") nil) (conj err "foo is required"))
(if (= (get doc "bar") nil) (conj err "bar is required"))
(if (not-empty err)
(prn err)
(
;do somthing
)
)
)
)
你可以告诉我,我是Clojure的新手,所以任何帮助都会感激不尽:)
答案 0 :(得分:1)
我会选择这样的东西:
(defn validate [data]
(letfn [(not-nil-v [data field msg errs]
(if (nil? (data field))
(conj errs msg)
errs))]
(if-let [val-res (seq (->> []
(not-nil-v data "foo" "foo is required")
(not-nil-v data "bar" "bar is required")))]
(println val-res)
(println "everything is ok"))))
#'user/validate
user> (validate {"foo" 1})
(bar is required)
nil
user> (validate {})
(foo is required bar is required)
nil
user> (validate {"foo" 1 "bar" 2})
everything is ok
nil