1

I have an update function such as:

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
    case msg of 
        NewImages (Ok images) ->
          ({model|images = images}, Cmd.none)

        NewImages (Err error) ->
          myFunction model

        NewUsers (Ok users) ->
          ({model|users = users}, Cmd.none)

        NewUsers (Err error) ->
          myFunction model

        [...]

and a function myFunction that I would like to call every time I get an HTTP.Error.

Apparently, _ cannot be used to match only the beginning of a pattern like in

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
    case msg of 
        NewImages (Ok images) ->
          ({model|images = images}, Cmd.none)

        NewUsers (Ok users) ->
          ({model|users = users}, Cmd.none)

        _ (Err error) ->
          myFunction model

        [...]

So, what would be the proper way to match all Http.Error in my update function?

1 Answer 1

5

I don't know how to match all Http.Errors in update function, but you can map all Http.Errors to a dedicated message.

type Msg
    = NewImages (List String)
    | ...
    | HttpError Http.Error

send : (a -> Msg) -> Request Http.Error a -> Cmd Msg
send tagger request =
    let
        makeMsg result =
            case result of
                Ok a ->
                    tagger a

                Err error ->
                    HttpError error
    in
        Http.send makeMsg request

-- and make an HTTP request like:
send NewImages request

Then you can match all your HTTP errors.

update msg model =
    case msg of
        NewImages images ->
            ({ model | images = images }, Cmd.none)

        ...

        HttpError error ->
            myFunction error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.