这可以通过使用checkStatus
类似于官方示例之一的自定义来实现。
如果响应状态码是 2xx 或 404,我们将声明checkStatus200
哪个通过。如果没有通过,它会调用默认checkStatus
函数来抛出适当的异常。
httpLbs
使用Request
using调用后checkStatus200
,我们可以检查状态码并返回Just
响应码或Nothing
.
import Data.Conduit.Binary (sinkFile)
import Network.HTTP.Types.Status (Status(..))
import Network.HTTP.Conduit
import qualified Data.Conduit as C
import Network
import Data.Default (def)
import qualified Data.ByteString.Lazy as LB
-- | @checkStatus@ implementation that accepts
-- 2xx status codes and 404. Calls default implementation
-- on other status codes (i.e. throws exception)
checkStatus200 st@(Status sc _) rh cj =
if (200 <= sc && sc < 300) || sc == 404
then Nothing
else (checkStatus def) st rh cj
-- | Download a HTTP link, returning @Nothing@ on 404 status code
downloadCatch404 :: String
-> IO (Maybe LB.ByteString)
downloadCatch404 url = withSocketsDo $ do
request <- parseUrl url
let request' = request { checkStatus = checkStatus200 }
res <- withManager $ httpLbs request'
let status = statusCode . responseStatus $ res
-- Return Nothing if status code == 404
return $ if status == 404
then Nothing
else Just $ responseBody res