Created
March 23, 2012 04:28
-
-
Save alexpw/2166820 to your computer and use it in GitHub Desktop.
Clojure - macro try-catch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; Approach 1, verbose | |
(defmacro try-catch [[lvl-fn fn] body] | |
(list 'try body | |
(list 'catch 'Exception 'e | |
(list lvl-fn 'e | |
(list ':name (list 'meta '#'fn)))))) | |
(macroexpand '(try-catch [info foo] (reduce + 0 (range 5)))) | |
;;=> (try (reduce + 0 (range 5)) (catch Exception e (info e (:name (meta (var fn)))))) | |
;; Approach 2, syntax-quote | |
(defmacro try-catch [[lvl-fn fn] body] | |
`(try | |
~body | |
(catch Exception e# | |
(~lvl-fn e# (str "Exception thrown trying to " (:name (meta #'~fn))))))) | |
(macroexpand '(try-catch [info foo] (throw (new Exception "test")))) | |
;;=> (try (throw (new Exception "test")) (catch java.lang.Exception e__1427__auto__ (info e__1427__auto__ (clojure.core/str "Exception thrown trying to " (:name (clojure.core/meta (var foo))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment