Skip to content

Commit c051c6d

Browse files
authored
Merge pull request #167 from sjshuck/on-error
Add Control.Monad.Error.Class.onError
2 parents a9509bc + ca0f98e commit c051c6d

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

Control/Monad/Error/Class.hs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ module Control.Monad.Error.Class (
4848
tryError,
4949
withError,
5050
handleError,
51+
onError,
5152
mapError,
5253
modifyError,
5354
) where
@@ -72,9 +73,9 @@ import qualified Control.Monad.Trans.RWS.CPS as CPSRWS
7273
import qualified Control.Monad.Trans.Writer.CPS as CPSWriter
7374
import Control.Monad.Trans.Class (lift)
7475
import Control.Exception (IOException, catch, ioError)
75-
import Control.Monad (Monad)
76+
import Control.Monad (Monad ((>>=), (>>)))
7677
import Data.Monoid (Monoid)
77-
import Prelude (Either (Left, Right), Maybe (Nothing), either, flip, (.), IO, pure, (<$>), (>>=))
78+
import Prelude (Either (Left, Right), Maybe (Nothing), either, flip, (.), IO, pure, (<$>))
7879

7980
{- |
8081
The strategy of combining computations that can throw exceptions
@@ -227,6 +228,14 @@ withError f = handleError (throwError . f)
227228
handleError :: MonadError e m => (e -> m a) -> m a -> m a
228229
handleError = flip catchError
229230

231+
-- | If an action throws an error, run a second action and rethrow the error.
232+
-- If the second action also throws an error, it takes precedence. Do not run
233+
-- the second action at all if the first succeeds.
234+
--
235+
-- @since 2.3.2
236+
onError :: MonadError e m => m a -> m b -> m a
237+
onError action1 action2 = action1 `catchError` \e -> action2 >> throwError e
238+
230239
-- | 'MonadError' analogue of the 'mapExceptT' function. The
231240
-- computation is unwrapped, a function is applied to the @Either@, and
232241
-- the result is lifted into the second 'MonadError' instance.

Control/Monad/Except.hs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ module Control.Monad.Except
4141
Error.tryError,
4242
Error.withError,
4343
Error.handleError,
44+
Error.onError,
4445
Error.mapError,
4546
Error.modifyError,
4647
-- * The ExceptT monad transformer

0 commit comments

Comments
 (0)