Welcome! Please see the About page for a little more info on how this works.

0 votes
in ClojureScript by

I'm writing a cljc library that needs to throw an error. This is how I tried to do it:

(def ErrorType #?(:clj java.lang.Exception
                  :cljc js/Error)

(throw (new ErrorType "message"))

But this code fails with an error saying "couldn't find class ErrorType". What is the correct way of doing this?

2 Answers

+1 vote
selected by
Best answer

I think you mean :cljs instead of :cljc.

I suspect the main issue here is that new is a special form that wants a symbol recognizable by the compiler, rather than a runtime variable. You can use ex-info portably, but if you want to leverage specific error types of the host platform, you might try an approach similar to this:

(defn oob-error
  #?(:clj (new ArrayIndexOutOfBoundsException message)
     :cljs (new js/RangeError message))

(throw (oob-error "message"))
+1 vote

I think you can construct an exception with ex-info and throw it in both Clojure and ClojureScript portably right?