Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Override clojure.spec.alpha/gensub for friendly exceptions for failed such-that - see
;; Normally the exception thrown by such-that does not point to the failed spec, which makes it useless
;; Eval this to override it and include `path` to the spec (and `form`, not sure which better)
(in-ns 'clojure.spec.alpha)
(defn- gensub
[spec overrides path rmap form]
;;(prn {:spec spec :over overrides :path path :form form})
(let [spec (specize spec)]
(if-let [g (c/or (when-let [gfn (c/or (get overrides (c/or (spec-name spec) spec))
(get overrides path))]
(gen* spec overrides path rmap))]
(gen/such-that #(valid? spec %) g {:max-tries 100
:ex-fn (fn [{:keys [max-tries]}]
(ex-info (str "Couldn't satisfy " (spec-name spec) " after " max-tries " tries.")
{:max max-tries
:path path
:sample-explain (->> (first (gen/sample g 1))
(explain-data spec)
(let [abbr (abbrev form)]
(throw (ex-info (str "Unable to construct gen at: " path " for: " abbr)
{::path path ::form form ::failure :no-gen}))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment