Skip to content

Commit 268493f

Browse files
committed
Add catchJust
1 parent 9e7a233 commit 268493f

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

docs/Monad/Error.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,17 @@ Laws:
3030
- Pure: `catchError (pure a) f = pure a`
3131

3232

33+
#### `catchJust`
34+
35+
``` purescript
36+
catchJust :: forall e m a b. (MonadError e m) => (e -> Maybe b) -> m a -> (b -> m a) -> m a
37+
```
38+
39+
This function allows you to provide a predicate for selecting the
40+
exceptions that you're interested in, and handle only those exceptons.
41+
If the inner computation throws an exception, and the predicate returns
42+
Nothing, then the whole computation will still fail with that exception.
43+
3344
#### `monadErrorEither`
3445

3546
``` purescript

src/Control/Monad/Error/Class.purs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,22 @@ class MonadError e m where
3333
throwError :: forall a. e -> m a
3434
catchError :: forall a. m a -> (e -> m a) -> m a
3535

36+
-- | This function allows you to provide a predicate for selecting the
37+
-- | exceptions that you're interested in, and handle only those exceptons.
38+
-- | If the inner computation throws an exception, and the predicate returns
39+
-- | Nothing, then the whole computation will still fail with that exception.
40+
catchJust :: forall e m a b. (MonadError e m)
41+
=> (e -> Maybe b) -- ^ Predicate to select exceptions
42+
-> m a -- ^ Computation to run
43+
-> (b -> m a) -- ^ Handler
44+
-> m a
45+
catchJust p act handler = catchError act handle
46+
where
47+
handle e =
48+
case p e of
49+
Nothing -> throwError e
50+
Just b -> handler b
51+
3652
instance monadErrorEither :: MonadError e (Either e) where
3753
throwError = Left
3854
catchError (Left e) h = h e

0 commit comments

Comments
 (0)