Fork me on GitHub
#clojure-spec
<
2016-11-16
>
gerrit11:11:33

I wonder if there is something built into spec already, that does the following: conform a value and throw an exception with an explanation of what violates the spec in case conform returns invalid. similar to s/assert but always on, as it should be used for internal conforming and validation, e.g. after reading from a database. I came up with this:

(defn conform-validate [spec x]
  (let [conformed (s/conform spec x)]
    (if (s/invalid? conformed)
      (throw (ex-info (str "spec violated: " (s/explain-str spec x))
                      (s/explain-data spec x)))
      conformed)))
any simpler approaches that I am missing or helper libraries that do this already?

bbloom22:11:18

^ I ran in to precisely that need almost immediately upon trying spec. I think it would be a good addition to the lib if it had a good name and insightful docstring. Maybe s/enforce and a docstring that contrasts with assert

bbloom22:11:07

although, to play devil’s advocate with myself, i found that when i did want this, i wanted to add extra data to the error via ex-info

Alex Miller (Clojure team)23:11:47

Rich considered it and ended up with assert so I don't think he plans to add it afaik

bbloom23:11:40

yeah, it’s a reasonable assumption that people would use the wrong one and/or it wouldn’t be particularly useful w/o wrapping it w/ extra data

Alex Miller (Clojure team)23:11:18

I expect people will make exactly what they want out of the available parts