3
votes

I'm wondering how to decode an Http.Error in elm and store it's data on my model.

I know that the error response is going to return this structure.

{
  error: "Some error message",
  ok: false
}

Here are my models and my Http request

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)

I was hoping I could handle this in FetchFail of my update like so.

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)

Any help is appreciated.

1
Your Error type alias seems unused. Better remove it (from the question if it was used elsewhere). - farmio

1 Answers

6
votes

Elm 0.17:

The Http.Error type is a union type that can hold the the response code if there was any.

type Error = Timeout | NetworkError | UnexpectedPayload String | BadResponse Int String

You can case over the err variable to access it.

FetchFail err ->
  case err of
    BadResponse code error ->
      -- handle error message
    _ ->
      -- other error

http://package.elm-lang.org/packages/evancz/elm-http/3.0.1/Http#Error


With elm 0.18 and the transition to elm-lang/http the Error type has been modified:

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