我想知道如何解码榆树中的Http.Error并将其数据存储在我的模型中.
我知道错误响应将返回此结构.
{
error: "Some error message",
ok: false
}
Run Code Online (Sandbox Code Playgroud)
这是我的模型和我的Http请求
type alias Model =
{ url = String
, result : String
, errorMessage : String
, error : Bool
}
model : Model
model =
{ url = ""
, result = ""
, errorMessage = ""
, error = False
}
-- make the request
makeRequest : String -> Cmd Msg
makeRequest url =
Task.perform FetchFail FetchSucceed (Http.get decodeTitle url)
-- decode the success response
decodeTitle : Json.Decoder String
decodeTitle =
Json.at ["title"] Json.string
-- decode the error
decodeError =
Json.object2 User
("error" := Json.string)
("ok" := Json.bool)
Run Code Online (Sandbox Code Playgroud)
我希望我可以在FetchFail我的更新中处理这个问题.
type Msg
= FetchTitle
| FetchSucceed String
| FetchFail Http.Error
update : Msg -> Model -> (Model, Cmd Msg)
update action model =
case action of
...
FetchFail err ->
let
error =
decodeError error
in
({ model | ok = error.ok, errorMessage = error.error}, Cmd.none)
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏.
榆树0.17:
Http.Error类型是一种联合类型,如果有的话,它可以保存响应代码.
类型错误=超时| NetworkError | UnexpectedPayload字符串| BadResponse Int String
您可以case通过err变量来访问它.
FetchFail err ->
case err of
BadResponse code error ->
-- handle error message
_ ->
-- other error
Run Code Online (Sandbox Code Playgroud)
http://package.elm-lang.org/packages/evancz/elm-http/3.0.1/Http#Error
使用elm 0.18并转换到elm-lang/http时,错误类型已被修改:
type Error
= BadUrl String
| Timeout
| NetworkError
| BadStatus (Response String)
| BadPayload String (Response String)
Run Code Online (Sandbox Code Playgroud)