Skip to content

Commit 6a79559

Browse files
committed
Merge pull request #16 from kRITZCREEK/try-function
adds a try function
2 parents 50ce994 + 1384aa8 commit 6a79559

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

bower.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
],
1919
"dependencies": {
2020
"purescript-eff": "^1.0.0-rc.1",
21-
"purescript-maybe": "^1.0.0-rc.1"
21+
"purescript-maybe": "^1.0.0-rc.1",
22+
"purescript-either": "^1.0.0-rc.1",
23+
"purescript-prelude": "^1.0.0-rc.1"
2224
}
2325
}

src/Control/Monad/Eff/Exception.purs

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,15 @@ module Control.Monad.Eff.Exception
1010
, throwException
1111
, catchException
1212
, throw
13+
, try
1314
) where
1415

1516
import Control.Monad.Eff (Eff)
1617
import Control.Semigroupoid ((<<<))
17-
18+
import Data.Either (Either(Right, Left))
1819
import Data.Maybe (Maybe(..))
1920
import Data.Show (class Show)
21+
import Prelude ((<$>), pure)
2022

2123
-- | This effect is used to annotate code which possibly throws exceptions
2224
foreign import data EXCEPTION :: !
@@ -80,3 +82,23 @@ foreign import catchException
8082
-- | `throwException <<< error`.
8183
throw :: forall eff a. String -> Eff (err :: EXCEPTION | eff) a
8284
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

Comments
 (0)