2016-11-17 47 views
2

這裏是傳遞的代碼版本Midje對宏失敗Clojure中

正常功能:即通過

(defn my-fn 
    [] 
    (throw (IllegalStateException.))) 

(fact 
    (my-fn) => (throws IllegalStateException)) 

這裏是它的宏版本:

(defmacro my-fn 
    [] 
    (throw (IllegalStateException.))) 

(fact 
    (my-fn) => (throws IllegalStateException)) 

其中失敗這裏是輸出:

LOAD FAILURE for example.dsl.is-test 
java.lang.IllegalStateException, compiling:(example/dsl/is_test.clj:14:3) 
The exception has been stored in #'*me, so `(pst *me)` will show the stack trace. 
FAILURE: 1 check failed. (But 12 succeeded.) 

這是我剛換DEFNdefmacro相同的代碼。

我不明白爲什麼這不起作用?

回答

4

事情是你的宏是錯誤的。當您的函數在運行時拋出錯誤時,宏將在編譯時拋出錯誤。以下內容應修復此行爲:

(defmacro my-fn 
    [] 
    `(throw (IllegalStateException.))) 

現在,您的宏調用將被替換爲拋出的異常。類似的東西:

(fact 
    (throw (IllegalStateException.)) => (throws IllegalStateException)) 
+0

非常感謝! –