gpt4 book ai didi

haskell - `wreq` Get/Post 带异常处理

转载 作者:行者123 更新时间:2023-12-02 14:41:03 31 4
gpt4 key购买 nike

我正在使用 wreq 进行一些 http 调用并希望捕获任何异常并返回 Either类型。我尝试了类似的方法,但无法弄清楚如何操作调用,以便它进行类型检查。

 -- exhaustive pattern match omitted here
safeGetUrl :: URL -> Maybe Login -> Maybe Password -> IO (Either String (Response LBS.ByteString))
safeGetUrl url (Just login) (Just pass) = do
let def = defaults
opts = def & auth ?~ basicAuth (BS.pack login) (BS.pack pass)
r <- getWith opts url `E.catch` handler
return $ Right r

where
handler :: HttpException -> Either String (Response LBS.ByteString)
handler (StatusCodeException s _ _) = do
return $ Left $ LBS.unpack (s ^. statusMessage)

我粘贴了下面的类型错误,但我知道上面的代码将无法编译。问题是r <- getWith opts url E.catch handler 。第一部分返回IO (Res...但异常处理程序返回 Either.. 。我尝试添加提升 getWith..进入Either但这也没有进行类型检查。

Couldn't match type ‘Either String (Response LBS.ByteString)’
with ‘IO (Response LBS.ByteString)’
Expected type: HttpException -> IO (Response LBS.ByteString)
Actual type: HttpException
-> Either String (Response LBS.ByteString)
In the second argument of ‘catch’, namely ‘handler’
In a stmt of a 'do' block: r <- getWith opts url `catch` handler

有没有办法捕获此异常并返回 IO Either类型?

最佳答案

自从 @jozefg 回答以来,API 发生了一些变化,并且答案不再编译。

这是可编译的更新版本:

import qualified Control.Exception     as E
import Control.Lens
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Lazy as LBS
import Network.HTTP.Client
import Network.Wreq as NW

type URL = String

type Login = String

type Password = String

safeGetUrl ::
URL
-> Maybe Login
-> Maybe Password
-> IO (Either String (Response LBS.ByteString))
safeGetUrl url (Just login) (Just pass) = do
let def = defaults
opts = def & auth ?~ basicAuth (BSC.pack login) (BSC.pack pass)
(Right <$> getWith opts url) `E.catch` handler
where
handler :: HttpException -> IO (Either String (Response LBS.ByteString))
handler (HttpExceptionRequest _ (StatusCodeException r _)) =
return $ Left $ BSC.unpack (r ^. NW.responseStatus . statusMessage)

关于haskell - `wreq` Get/Post 带异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36361611/

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