Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RWExceptionT example
(defn stuff
[base]
(m/mlet rwx/rwexception-ctx
[_ (writer/tell [:base base])
{offs :config/offset} (reader/ask)
_ (writer/tell [:config/offset offs])
tot (m/return (+ base offs))
_ (writer/tell [:total tot])]
(m/return tot)))
(defn handle-stuff
[& args]
(m/mlet rwx/rwexception-ctx
(e/handle
(apply stuff args)
(fn [left right]
(if (some? left)
(m/mlet rwx/rwexception-ctx
[_ (writer/tell [:ex :handled])]
(m/return (ex-message left)))
(m/mlet rwx/rwexception-ctx
[_ (writer/tell [:ex :none])]
(m/return right)))))))
;; writer log is preserved through errors,
;; and you can log in handle, catch and finally
(r/run (handle-stuff 100)
{:monad.reader/env {:config/offset 100}})
=>
{:monad.writer/output {:base [100],
:config/offset [100],
:total [200],
:ex [:none]},
:monad/val 200}
;; here's how an error gets caught/handled
(r/run (handle-stuff 100)
{:monad.reader/env {:config/offset :foo}})
{:monad.writer/output {:base [100],
:config/offset [:foo],
:ex [:handled]},
:monad/val "class clojure.lang.Keyword cannot be cast to class java.lang.Number (clojure.lang.Keyword is in unnamed module of loader 'app'; java.lang.Number is in module java.base of loader 'bootstrap')"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment