Use or abuse of Monad Error Transformer

Background

I work with a monad consisting of a stack of transformers, one of which is ErrorT. So my monad implements the MonadError class, and throwError is a valid operator. I want to throw errors only when a certain condition is fulfilled. I tend to do the following:

 if badCondition then throwError "You did a bad, bad thing..." else return () doGoodThings [...] 

If you look at this, I can even generalize it to the following:

 throwErrorWhen :: (MonadError em) => Bool -> e -> m () throeErrorWhen cond err = if cond then throwError e else return () 

In fact, this seems so obvious that I was surprised that this is not a MonadError library.

Question

Is there a better / more correct way to increase the error only if some condition is met?

+4
source share
1 answer

There's a when function in Control.Monad that evaluates its second argument if the boolean value is true:

 when :: Monad m => Bool -> m () -> m () 

So you get

 throwErrorWhen cond e = when cond (throwError e) 
+13
source

All Articles