Skip to content

Instantly share code, notes, and snippets.

@mccraigmccraig
Last active February 18, 2021 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mccraigmccraig/81ae4e4ff90334676589515d2c570430 to your computer and use it in GitHub Desktop.
Save mccraigmccraig/81ae4e4ff90334676589515d2c570430 to your computer and use it in GitHub Desktop.
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