module Network.Salvia.Handler.Error
( hError
, hCustomError
, hIOError
, hSafeIO
, catchIO
)
where
import Control.Monad.Trans
import Data.Record.Label
import Network.Protocol.Http
import Network.Salvia.Interface
import System.IO.Error
hError :: (HttpM Response m, SendM m) => Status -> m ()
hError e = hCustomError e
(concat ["[", show (codeFromStatus e), "] ", show e, "\n"])
hCustomError :: (HttpM Response m, SendM m) => Status -> String -> m ()
hCustomError e m =
do response $
do status =: e
contentLength =: Just (length m)
contentType =: Just ("text/plain", Nothing)
send m
hIOError :: (HttpM Response m, SendM m) => IOError -> m ()
hIOError e
| isDoesNotExistError e = hError NotFound
| isAlreadyInUseError e = hError ServiceUnavailable
| isPermissionError e = hError Forbidden
| otherwise = hError InternalServerError
hSafeIO
:: (MonadIO m, HttpM Response m, SendM m)
=> IO a -> (a -> m ()) -> m ()
hSafeIO io h = liftIO (try io) >>= either hIOError h
catchIO :: MonadIO m => IO a -> a -> m a
catchIO a b = liftIO (a `catch` (const (return b)))