Skip to content

Commit

Permalink
Handle only needed exceptions with try*
Browse files Browse the repository at this point in the history
  • Loading branch information
darkleaf committed Dec 30, 2024
1 parent 5f2d9d2 commit 4d90c18
Showing 1 changed file with 40 additions and 4 deletions.
44 changes: 40 additions & 4 deletions src/darkleaf/di/core.clj
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,42 @@
x#
(?? ~@next))))


;; https://clojure.atlassian.net/browse/CLJ-2124
;; https://github.com/Gonzih/feeds2imap.clj/blob/master/src/feeds2imap/macro.clj
(defmacro ^:pirvate try*
"Macro to catch multiple exceptions with one catch body.
Usage:
(try*
(println :a)
(println :b)
(catch* [A B] e (println (class e)))
(catch C e (println :C))
(finally (println :finally-clause)))
Will be expanded to:
(try
(println :a)
(println :b)
(catch A e (println (class e)))
(catch B e (println (class e)))
(catch C e (println :C))
(finally (println :finally-clause)))
"
[& body]
(letfn [(catch*? [form]
(and (seq form)
(= (first form) 'catch*)))
(expand [[_catch* classes & catch-tail]]
(map #(list* 'catch % catch-tail) classes))
(transform [form]
(if (catch*? form)
(expand form)
[form]))]
(cons 'try (mapcat transform body))))


(defn- index-of
"Returns the index of the first occurrence of `x` in `xs`."
[^List xs x]
Expand Down Expand Up @@ -144,10 +180,10 @@
(recur tail (assoc built-map key obj)))))))))

(defn- try-run [proc]
(try
(try*
(proc)
nil
(catch Throwable ex
(catch* [Exception AssertionError] ex
ex)))

(defn- try-run-all [procs]
Expand All @@ -168,9 +204,9 @@
(try-run-all stops)))

(defn- try-build [ctx key]
(try
(try*
(build ctx key)
(catch Throwable ex
(catch* [Exception AssertionError] ex
(let [exs (try-stop-started ctx)
exs (cons ex exs)]
(throw-many! exs)))))
Expand Down

0 comments on commit 4d90c18

Please sign in to comment.