Skip to content

Instantly share code, notes, and snippets.

@overthink overthink/die-on-nils.clj
Last active Dec 15, 2016

Embed
What would you like to do?
Sort of nice nil checker in Clojure
(defn- ellipses-if-long
"Append \"...\" to string version of x if x's length exceeds n."
([x] (ellipses-if-long x 50))
([x n]
(assert (pos? n) "n must be positive")
(let [s (str x)]
(if (> (.length s) n)
(str (subs s 0 n) "...")
s))))
(defmacro non-nil!
"If any of exprs evaluates to nil throw an exception containing a snippet of
the offending code in the message. Returns nil when it doesn't throw. Note
that each of exprs (until one evaluates to nil) will be evaluated here, so
don't use with side-effecting expressions."
[& exprs]
`(do
~@(for [expr exprs]
`(when (nil? ~expr) ; expr is actually evaluated here
(throw
(ex-info (format "'%s' evaluated to nil"
(ellipses-if-long '~expr))
{:expr '~expr}))))
nil))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.