File tree Expand file tree Collapse file tree 1 file changed +17
-1
lines changed Expand file tree Collapse file tree 1 file changed +17
-1
lines changed Original file line number Diff line number Diff line change @@ -5,7 +5,7 @@ module Control.Monad.Error.Class where
5
5
import Prelude
6
6
7
7
import Data.Maybe (Maybe (..))
8
- import Data.Either (Either (..))
8
+ import Data.Either (Either (..), either )
9
9
10
10
-- | The `MonadError` type class represents those monads which support errors via
11
11
-- | `throwError` and `catchError`.
@@ -54,3 +54,19 @@ instance monadErrorMaybe :: MonadError Unit Maybe where
54
54
throwError = const Nothing
55
55
catchError Nothing f = f unit
56
56
catchError (Just a) _ = Just a
57
+
58
+ -- | Make sure that a resource is cleaned up in the event of an exception. The
59
+ -- | release action is called regardless of whether the body action throws or
60
+ -- | returns.
61
+ withResource
62
+ :: forall e m r a
63
+ . MonadError e m
64
+ => m r
65
+ -> (r -> m Unit )
66
+ -> (r -> m a )
67
+ -> m a
68
+ withResource acquire release kleisli = do
69
+ resource <- acquire
70
+ result <- (Right <$> kleisli resource) `catchError` (pure <<< Left )
71
+ release resource
72
+ either throwError pure result
You can’t perform that action at this time.
0 commit comments