模式匹配所有 HTTP 错误
Pattern match all the HTTP errors
我有一个更新功能,例如:
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
[...]
和一个函数 myFunction
,我想在每次得到 HTTP.Error 时调用它。
显然,_
不能用于仅匹配模式的开头,如
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 的正确方法是什么?
我不知道如何在更新函数中匹配所有 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
我有一个更新功能,例如:
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
[...]
和一个函数 myFunction
,我想在每次得到 HTTP.Error 时调用它。
显然,_
不能用于仅匹配模式的开头,如
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 的正确方法是什么?
我不知道如何在更新函数中匹配所有 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