Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Servant Custom JSON parsing errors

Given the following Servant server:

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}

module ServantSample (main) where

import Data.Aeson
import Data.Aeson.TH
import Network.Wai
import Network.Wai.Handler.Warp
import Servant

data Spec = Spec
  { schema :: Object
  } deriving (Eq, Show)
$(deriveJSON defaultOptions ''Spec)

type Api = ReqBody '[JSON] Spec :> Post '[JSON] NoContent

server :: Server Api
server = postDoc

postDoc :: Spec -> Handler NoContent
postDoc _ = return NoContent

api :: Proxy Api
api = Proxy

app :: Application
app = serve api server

main :: IO ()
main = run 8080 app

...and the following curl to a running instance of the above server:

curl localhost:8080 -H 'Content-Type: application/json' --data '{"schema": "I am not an object but I should be!"}'

I get back:

Error in $.schema: expected HashMap ~Text v, encountered String

Is there a way to intercept the Aeson error and replace it with something that doesn't leak implementation details to the client? As far as I can tell, this all happens behind the scenes in Servant's machinery, and I can't find any documentation about how to hook into it.

For instance, I'd love to return something like:

Expected a JSON Object under the key "schema", but got the String "I am not an object but I should be!"

Thanks!

like image 598
adlaika Avatar asked Oct 23 '25 21:10

adlaika


1 Answers

Writing the FromJSON instance by hand solves at least half of your problem.

instance FromJSON Spec where
  parseJSON (Object o) = do
    schema <- o .: "schema"
    case schema of
      (Object s) -> pure $ Spec s
      (String s) -> fail $ "Expected a JSON Object under the key \"schema\", but got the String \"" ++ unpack s ++ "\"\n"
      _          -> fail $ "Expected a JSON Object under the key \"schema\", but got the other type"
  parseJSON wat = typeMismatch "Spec" wat

Your curl command then returns:

Error in $: Expected a JSON Object under the key "schema", but got the String "I am not an object but I should be!"

You can obviously check for the different Value type constructors from Aeson and factor it into a separate function.

Got the code from looking at the implementation of Data.Aeson.Types.typeMismatch

like image 79
Mikkel Avatar answered Oct 26 '25 12:10

Mikkel