module Serokell.Util.Exceptions
( TextException (..)
, throwText
, EmptyException (..)
, throwEmpty
, eitherToFail
) where
import Universum
import Control.Exception (Exception (..), SomeException)
import qualified Control.Monad as Monad
import Data.Text (Text)
import qualified Data.Text.Buildable
import qualified Data.Text.Format as F
import Data.Typeable (Typeable)
import Formatting (bprint, stext, string, (%))
instance Buildable SomeException where
build e =
case fromException e of
Nothing -> bprint string (displayException e)
Just (TextException msg) -> bprint ("TextException: " %stext) msg
newtype TextException = TextException
{ teMessage :: Text
} deriving (Show,Typeable)
instance Exception TextException
instance Buildable TextException where
build = F.build "TextException: {}" . F.Only . teMessage
throwText :: MonadThrow m
=> Text -> m a
throwText = throwM . TextException
data EmptyException = EmptyException
deriving (Show, Typeable)
instance Exception EmptyException
throwEmpty :: MonadThrow m => m a
throwEmpty = throwM EmptyException
eitherToFail :: (Monad m, e ~ SomeException) => Either e a -> m a
eitherToFail = either (Monad.fail . show) return