module Cachix.API.Error
  ( escalate,
    escalateAs,
  )
where

import Control.Monad.Catch (MonadThrow (throwM))
import Protolude

-- | Examples:
--    > escalate . maybeToEither err404
--
--  | Note that exceptions gets handled by warp and logged (user sees just "Internal server")
escalateAs ::
  (Exception exc, MonadThrow m) =>
  (l -> exc) ->
  Either l a ->
  m a
escalateAs :: (l -> exc) -> Either l a -> m a
escalateAs l -> exc
f = (l -> m a) -> (a -> m a) -> Either l a -> m a
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (exc -> m a
forall (m :: * -> *) e a. (MonadThrow m, Exception e) => e -> m a
throwM (exc -> m a) -> (l -> exc) -> l -> m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. l -> exc
f) a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure

escalate ::
  (Exception exc, MonadThrow m) =>
  Either exc a ->
  m a
escalate :: Either exc a -> m a
escalate = (exc -> exc) -> Either exc a -> m a
forall exc (m :: * -> *) l a.
(Exception exc, MonadThrow m) =>
(l -> exc) -> Either l a -> m a
escalateAs exc -> exc
forall a. a -> a
identity