(ns spec-test.core
  (:require [clojure.spec :as s]))

(s/def :user/name string?)
(s/def :common/user (s/keys :req [:user/name]))

; first version of name (using :pre)
(defn name [user]
  {:pre [(s/valid? :common/user user)]}
  (-> user :user/name))

; This statement works ok and returns "Elon":
(name {:user/name "Elon"})

; but this statement...
(name {:x "Elon"})

;...will throw:
CompilerException java.lang.AssertionError:
Assert failed: (s/valid? :common/user user)

; ...but then I don't get as much information
; about the error as if I would have called:
(s/explain :common/user {:x "Elon"})

;...which also contains the predicate:
val: {:x "Elon"} fails spec: :common/user
predicate: (contains? % :user/name)

; (second version of name - more verbose)
; or do I need to wite it like this:
(defn name [user]
  (let [parsed (s/conform :common/user user)]
    (if (= parsed ::s/invalid)
      (throw (ex-info "Invalid input" (s/explain-data :common/user user)))
      (-> user :user/name))))

; so that:
(name {:x "Elon"})

; ...will return:
CompilerException clojure.lang.ExceptionInfo:
  Invalid input #:clojure.spec{:problems}
    ({:path [], :pred (contains? % :user/name),
      :val {:x "Elon"}, :via [:common/user], :in []})

; It should be nice if I could be able to write it like this
; (or similar, to get a better error message):
(defn name [user]
  {:pre [(s/explain :common/user user)]}
  (-> user :user/name))

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
--- 
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to clojure+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to