给定以下Servant服务器:

{-# 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


...以及以下对上述服务器正在运行的实例的卷曲:

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


我回来了:

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


有没有办法拦截Aeson错误并将其替换为不会将实现细节泄漏给客户端的内容?据我所知,这一切都是在Servant机器的幕后发生的,我找不到任何有关如何将其连接的文档。

例如,我很想返回以下内容:

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


谢谢!

最佳答案

手动编写FromJSON实例至少可以解决一半的问题。

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


然后,您的curl命令返回:

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


您显然可以检查Aeson中不同的Value类型构造函数,并将其分解为一个单独的函数。

通过查看Data.Aeson.Types.typeMismatch的实现获得了代码

08-19 01:55