2016-11-17 58 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

非常感谢! –