gpt4 book ai didi

json - Haskell Servant 自定义 JSON 解析错误

转载 作者:行者123 更新时间:2023-12-05 01:18:30 26 4
gpt4 key购买 nike

给定以下 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:

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 的实现获得代码

关于json - Haskell Servant 自定义 JSON 解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50615514/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com