@@ -10,13 +10,15 @@ module Control.Monad.Eff.Exception
1010 , throwException
1111 , catchException
1212 , throw
13+ , try
1314 ) where
1415
1516import Control.Monad.Eff (Eff )
1617import Control.Semigroupoid ((<<<))
17-
18+ import Data.Either ( Either (Right, Left))
1819import Data.Maybe (Maybe (..))
1920import Data.Show (class Show )
21+ import Prelude ((<$>), pure )
2022
2123-- | This effect is used to annotate code which possibly throws exceptions
2224foreign import data EXCEPTION :: !
@@ -80,3 +82,23 @@ foreign import catchException
8082-- | `throwException <<< error`.
8183throw :: forall eff a . String -> Eff (err :: EXCEPTION | eff ) a
8284throw = throwException <<< error
85+
86+ -- | Runs an Eff and returns eventual Exceptions as a `Left` value. If the
87+ -- | computation succeeds the result gets wrapped in a `Right`.
88+ -- |
89+ -- | For example:
90+ -- |
91+ -- | ```purescript
92+ -- | -- Notice that there is no EXCEPTION effect
93+ -- | main :: forall eff. Eff (console :: CONSOLE, fs :: FS | eff) Unit
94+ -- | main = do
95+ -- | result <- try (readTextFile UTF8 "README.md")
96+ -- | case result of
97+ -- | Right lines ->
98+ -- | Console.log ("README: \n" <> lines )
99+ -- | Left error ->
100+ -- | Console.error ("Couldn't open README.md. Error was: " <> show error)
101+ -- | ```
102+
103+ try :: forall eff a . Eff (err :: EXCEPTION | eff ) a -> Eff eff (Either Error a )
104+ try action = catchException (pure <<< Left ) (Right <$> action)
0 commit comments