@@ -10,13 +10,15 @@ module Control.Monad.Eff.Exception
10
10
, throwException
11
11
, catchException
12
12
, throw
13
+ , try
13
14
) where
14
15
15
16
import Control.Monad.Eff (Eff )
16
17
import Control.Semigroupoid ((<<<))
17
-
18
+ import Data.Either ( Either (Right, Left))
18
19
import Data.Maybe (Maybe (..))
19
20
import Data.Show (class Show )
21
+ import Prelude ((<$>), pure )
20
22
21
23
-- | This effect is used to annotate code which possibly throws exceptions
22
24
foreign import data EXCEPTION :: !
@@ -80,3 +82,23 @@ foreign import catchException
80
82
-- | `throwException <<< error`.
81
83
throw :: forall eff a . String -> Eff (err :: EXCEPTION | eff ) a
82
84
throw = 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