Search code examples
clojurepre

how to raise a exception in clojure pre-expr?


clojure's pre-expr seems cool, but does it possible if I want to raise an Exception when the :pre is false?

thanks.


Solution

  • You can use Dire instead

    (ns mytask
      (:require [dire.core :refer [with-precondition! with-handler!]]))
    
    (defn add-one [n]
      (inc n))
    
    (with-precondition! #'add-one
      "An optional docstring."
      ;;; Name of the precondition
      :not-two
      (fn [n & args]
        (not= n 2)))
    
    (with-handler! #'add-one
      {:precondition :not-two}
      (fn [e & args] (apply str "Precondition failure for argument list: " (vector args))))
    
    (add-one 2) ; => "Precondition failure for argument list: (2)"