Skip to content

Commit

Permalink
replace scotty deprecated raise with scotty throw for 500 errors
Browse files Browse the repository at this point in the history
replace deprecated scotty param function
resolves #372
  • Loading branch information
agentm committed Aug 21, 2024
1 parent e78ce7b commit c3fc5c7
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions examples/Plantfarm.hs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@

{-# LANGUAGE DerivingVia #-}


import Control.Monad.Catch (Exception)
import Codec.Winery (Serialise, WineryVariant(WineryVariant))
import Control.DeepSeq (NFData)
import Data.Aeson (FromJSON, ToJSON(toEncoding, toJSON))
import Data.Data (Proxy(Proxy))
import Data.Either (lefts, rights)
import Data.Functor (($>))
import Data.Text as T (Text)
import qualified Data.Text.Lazy as TL (pack)
import Data.Text as T (Text,pack)
import GHC.Generics (Generic)
import qualified ProjectM36.Base as Base
import ProjectM36.DatabaseContext
Expand Down Expand Up @@ -147,7 +146,7 @@ main = do

-- retrieve a plant by name
S.get "/plant/:name" $ do
n <- S.param "name"
n <- S.pathParam "name"
e <- liftIO $ getPlant c n
p <- handleWebError e
S.json p
Expand All @@ -170,7 +169,7 @@ main = do
-- watering the plant having the provided name.
-- This will water the plant and might let it progress to the next stage. It might also die.
S.post "/plant/water/:name" $ do
n <- S.param "name"
n <- S.pathParam "name"
e <- liftIO $ waterPlant c n
p <- handleWebError e
S.json p
Expand All @@ -190,14 +189,14 @@ main = do

-- deleting all plants at a specific stage
S.delete "/plants?stage=:stage" $ do
s <- S.param "stage"
s <- S.pathParam "stage"
e <- liftIO $ deletePlantsByStage c s
p <- handleWebError e
S.json p

-- deleting all plants at a specific stage
S.delete "/plants" $ do
s <- S.param "name"
s <- S.queryParam "name"
e <- liftIO $ deletePlantByName c s
p <- handleWebError e
S.json p
Expand All @@ -208,15 +207,20 @@ main = do
ps <- handleWebErrors e
S.json ps

data WebError = WebError T.Text
deriving Show

instance Exception WebError

handleWebError :: Either Err b -> S.ActionM b
handleWebError (Left e) = S.raise (TL.pack $ "An error occurred:\n" <> show e)
handleWebError (Left e) = S.throw (WebError (T.pack $ "An error occurred:\n" <> show e))
handleWebError (Right v) = pure v

handleWebErrors :: [Either Err b] -> S.ActionM [b]
handleWebErrors e = do
case lefts e of
[] -> pure (rights e)
l -> S.raise (TL.pack $ "Errors occurred:\n" <> concatMap ((<>"\n") . show) l)
l -> S.throw (WebError (T.pack $ "Errors occurred:\n" <> concatMap ((<>"\n") . show) l))


-- | watering a plant and thereby possibly updating its stage
Expand Down

0 comments on commit c3fc5c7

Please sign in to comment.