Background
I am working with a monad built of a stack of transformers one of which is ErrorT. My monad therefore implements the MonadError
class and throwError
is a valid statement. I want to throw and error only when a certain condition is met. I am inclined to do the following:
if badCondition
then throwError "You did a bad, bad thing..."
else return ()
doGoodThings
[...]
In looking at this I think I can even generalize it to the following:
throwErrorWhen :: (MonadError e m) => Bool -> e -> m ()
throeErrorWhen cond err = if cond then throwError e else return ()
In fact this seems so obvious that I was surprised that it was not the MonadError Library.
Question:
Is there a better/more correct way to raise an error only is some condition is met?
There's the when
function in Control.Monad
that evaluates its 2nd argument if the Boolean is true:
when :: Monad m => Bool -> m () -> m ()
So you get,
throwErrorWhen cond e = when cond (throwError e)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With