Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A simple servant sample of error
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
import Control.Monad.IO.Class -- liftIO
import Control.Monad.Trans.Except -- Handler
import Data.Aeson.Types -- JSON
import Data.Aeson.Parser -- JSON
import GHC.Generics
import Network.Wai.Handler.Warp
import Servant
data RetDiv = RetDiv { fst :: Double, snd :: Double, ret :: Double} deriving (Eq, Show, Generic)
instance ToJSON RetDiv
type MyAPI = "div" :> Capture "fst" Double :> Capture "snd" Double:> Get '[JSON] RetDiv
div' :: Double -> Double -> Handler RetDiv
div' f s = do
liftIO $ (putStrLn $ logDiv f s )
if s == 0
then throwError err400 {errBody="zero division"}
else return $ RetDiv f s (f/s)
logDiv :: Double -> Double -> String
logDiv f s = (show f) ++ "/" ++ (show s) ++ "=" ++ (show (f / s))
myServer :: Server MyAPI
myServer = div'
myProxy :: Proxy MyAPI
myProxy = Proxy
myApp :: Application
myApp = serve myProxy myServer
main :: IO ()
main = run 8081 myApp
Owner

naoto-ogawa commented Feb 19, 2017

$ curl -i http://127.0.0.1:8081/div/5/4
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Date: Sat, 18 Feb 2017 11:30:30 GMT
Server: Warp/3.2.9
Content-Type: application/json

$ curl -i http://127.0.0.1:8081/div/5/0
HTTP/1.1 303 See Other
Transfer-Encoding: chunked
Date: Sat, 18 Feb 2017 11:31:12 GMT
Server: Warp/3.2.9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment