Skip to content

Instantly share code, notes, and snippets.

@naoto-ogawa
Created January 29, 2017 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naoto-ogawa/e1c882919f59a6188b0df1006eccefd8 to your computer and use it in GitHub Desktop.
Save naoto-ogawa/e1c882919f59a6188b0df1006eccefd8 to your computer and use it in GitHub Desktop.
Exception handling by try in Servant
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
import Control.Exception as E
import Servant
import Control.Monad.IO.Class -- liftIO
import Network.Wai.Handler.Warp -- run
type FileRead03 = "sample03.txt" :> Get '[PlainText] String
myAPI03 :: Proxy FileRead03
myAPI03 = Proxy
app03 :: Application
app03 = serve myAPI03 server03
server03 :: Server FileRead03
server03 = do
ret <- liftIO (readF "sample03.txt")
case ret of
Left e -> throwError err404 {errBody="file error"}
Right s -> return s
readF :: String -> IO (Either SomeException String)
readF x = E.try (readFile x)
main03 :: IO ()
main03 = run 8080 app03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment