How to access: call ,: through and: trace exception keys in Clojure?

I could not find a way to access :cause, :via and :trace exception keys.

Here is the code:

 (try (throw (IllegalArgumentException. "1")) (catch Exception e e)) 

Output:

 #error{:cause "1", :via [{:type java.lang.IllegalArgumentException, :message "1", :at [user$eval4073 invokeStatic "form-init5592296091748814678.clj" 1]}], :trace [[user$eval4073 invokeStatic "form-init5592296091748814678.clj" 1] [user$eval4073 invoke "form-init5592296091748814678.clj" 1] [clojure.lang.Compiler eval "Compiler.java" 6927] [clojure.lang.Compiler eval "Compiler.java" 6890] [clojure.core$eval invokeStatic "core.clj" 3105] [clojure.core$eval invoke "core.clj" 3101] [clojure.main$repl$read_eval_print__7408$fn__7411 invoke "main.clj" 240] ....]} 

PS: (: via e) does not work.

+5
source share
1 answer

Clojure (JVM) will throw a Java exception object when an exception occurs. Clojure converts this to data using the Throwable->map function, and then prints it for you. You can call this function yourself:

 user=> (try (throw (Exception. "BOOM!")) (catch Exception e (Throwable->map e))) {:cause "BOOM!", :via [{:type java.lang.Exception, :message "BOOM!", :at [user$eval1 invokeStatic "NO_SOURCE_FILE" 1]}], :trace [[user$eval1 invokeStatic "NO_SOURCE_FILE" 1] ...]} 

Then you can simply use regular keyword accessories for the returned data:

 user=> (println (:cause *1) (first (:via *1))) BOOM! {:type java.lang.Exception, :message BOOM!, :at [user$eval7 invokeStatic NO_SOURCE_FILE 4]} 
+10
source

Source: https://habr.com/ru/post/1263751/


All Articles