It was surprisingly difficult for me to define a macro for error handling in both clj and cljs . I assumed that it was easy to replace Exceptionwith js/Error, but it turned out to be more complicated.
First I tried this:
(defmacro my-macro
[& forms]
`(try
~@forms
(catch #?(:clj Exception :cljs js/Error) e#
,,,)))
But it caused Exceptionevery time. Soon, I realized that the problem was that the macro was called during compilation of my cljs files that occur in the clj environment . Therefore, I would need to return a macro of the form that would allow the correct exception class at runtime. I tried this:
(def exception-class
(defmacro my-macro
[& forms]
`(try
~@forms
(catch exception-class e#
,,,)))
cljs, clj!!! , JVM Clojure (-) . Exception .
, , :
(def fake-java
(defmacro my-macro
[& forms]
`(let [~'java fake-java]
(try
~@forms
(catch Exception e#
,,,))))
Exception java.lang.Exception, clj, cljs.
, ? JVM Clojure , ClojureScript ?
ClojureMostly , :
(defmacro my-macro
[& forms]
`(try
~@forms
(catch ~(if (:ns &env) 'js/Error 'Exception) e#
,,,)))