Error handling in clojure

The with macro isn’t required in Clojure.

Where you would do:

with {:ok, result1} <- can_fail(),
     {:ok, result2} <- can_also_fail(result1)
do
  handle_success(result2)
else
  {:error, error} -> handle_error(error)
end

You just do what I did above again:

(try
  (-> (can-fail)
      (can-also-fail)
      (handle-success))
  (catch Exception error
    (handle-error error)))

You can think of it like everything in Clojure returns result or Exception. When things succeed, you don’t need to destructure the return value, since it returns the result as is, you can just use it, so no need for pattern-matching on success. Then on error, you also need not do anything, unless you want to, in which case you try/catch it. Otherwise the error is raised and will crash the process.

3 Likes