模式匹配所有HTTP错误

时间:2017-10-04 06:34:35

标签: pattern-matching elm

我有更新功能,例如:

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

        [...]

以及每次收到HTTP.Error时我想调用的函数myFunction

显然,_不能仅用于匹配模式的开头,如

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

        [...]

那么,在我的更新函数中匹配所有Http.Error的正确方法是什么?

1 个答案:

答案 0 :(得分:5)

我不知道如何匹配更新功能中的所有Http.Error,但您可以将所有Http.Error映射到专用消息。

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

然后您可以匹配所有HTTP错误。

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

        ...

        HttpError error ->
            myFunction error