榆木0.19:如何在使用elm / http 2.0.0接收BadStatus时获取请求体

问题描述 投票:3回答:1

elm / http 1.0.0将Http.Error定义为

type Error
    = BadUrl String
    | Timeout
    | NetworkError
    | BadStatus (Response String)
    | BadPayload String (Response String)

但2.0.0改为

type Error
    = BadUrl String
    | Timeout
    | NetworkError
    | BadStatus Int
    | BadBody String

当接收BadStatus时,我无法获取请求的正文,只有状态码。在docs中,Evan为此提出了解决方案,但我不明白如何使其发挥作用。

如果我们定义我们自己的expectJson类似于

expectJson : (Result Http.Error a -> msg) -> D.Decoder a -> Expect msg
expectJson toMsg decoder =
  expectStringResponse toMsg <|
    \response ->
      case response of
        Http.BadStatus_ metadata body ->
          Err (Http.BadStatus metadata.statusCode)
        ...

然后我们可以访问元数据和正文,但我该如何使用它们?我应该定义自己的myBadStatus并返回它吗?

Http.BadStatus_ metadata body ->
  Err (myBadStatus metadata.statusCode body)

这会有用吗?

我需要的是转换以下代码:

myErrorMessage : Http.Error -> String
myErrorMessage error =
    case error of
        Http.BadStatus response ->
            case Decode.decodeString myErrorDecoder response.body of
                Ok err ->
                    err.message
                Err e ->
                    "Failed to parse JSON response."
        ...

谢谢。

http elm
1个回答
1
投票

编辑22/4/2019:我更新了http-extras版本2.0+的答案,其中包含一些API更改。感谢Berend de Boer指出这一点!

下面的答案给出了一个解决方案,使用我编写的包(根据请求),但您不必使用该包!我写了一篇关于如何从HTTP响应中提取详细信息的entire article,它包括多个不需要包的Ellie示例,以及使用该包的示例。


正如Francesco所提到的,我使用类似的方法创建了一个用于此目的的包:https://package.elm-lang.org/packages/jzxhuang/http-extras/latest/

具体来说,模块使用Http.Detailed。它定义了一种错误类型,可以在错误时保持原始主体:

type Error body
    = BadUrl String
    | Timeout
    | NetworkError
    | BadStatus Metadata body Int
    | BadBody Metadata body String

提出这样的请求:

type Msg
    = MyAPIResponse (Result (Http.Detailed.Error String) ( Http.Metadata, String ))

sendRequest : Cmd Msg
sendRequest =
    Http.get
        { url = "/myapi"
        , expect = Http.Detailed.expectString MyAPIResponse

在您的更新中,处理结果,包括在BadStatus时解码正文:

update msg model =
    case msg of
        MyAPIResponse httpResponse ->
            case httpResponse of
                Ok ( metadata, respBody ) ->
                    -- Do something with the metadata if you need! i.e. access a header

                Err error ->
                    case error of
                        Http.Detailed.BadStatus metadata body statusCode ->
                            -- Try to decode the body the body here...

                        ...

        ...

感谢Francisco与我联系,希望这个答案可以帮助任何面临与OP相同问题的人。

© www.soinside.com 2019 - 2024. All rights reserved.