我正在执行Elm任务,以从API解码JSON。我遇到的问题是我编写的解码器与JSON不匹配,因此我想显示该错误。但是我无法将错误消息从#Http.Error#类型转换为#String#带toString功能的Elm类型。这是代码:
type Model =
Loading
| Failure String
| Success (List WishlistItem)
| NoData
update msg model =
case msg of
GotItems (Ok result) ->
(Success result.data.wish_list_items, Cmd.none)
GotItems (Err errorString) ->
(Failure (toString errorString), Cmd.none)
????????
Run Code Online (Sandbox Code Playgroud)
错误是:
命名错误-我找不到
toString变量:168 | (失败(toString errorString),Cmd.none)
我尝试过,Basics.toString但没有用。谁能帮我指出问题所在?
P / s 1:我正在使用Elm 0.19
P / s 2:使用NoRedInk/elm-decode-pipeline包解码JSON时,还有另一种方法可以找到问题吗?我尝试过,Debug.log但它只是打印了function,不知道如何调试。真的很难知道问题出在哪里。
如果返回Http.Error,它将有五个可能的值:
type Error
= BadUrl String
| Timeout
| NetworkError
| BadStatus Int
| BadBody String
Run Code Online (Sandbox Code Playgroud)
如果是使用JSON解码的问题,这将是BadBody,和String将是从JSON解码器的错误信息。您可能需要这样的功能:
errorToString : Http.Error -> String
errorToString error =
case error of
BadUrl url ->
"The URL " ++ url ++ " was invalid"
Timeout ->
"Unable to reach the server, try again"
NetworkError ->
"Unable to reach the server, check your network connection"
BadStatus 500 ->
"The server had a problem, try again later"
BadStatus 400 ->
"Verify your information and try again"
BadStatus _ ->
"Unknown error"
BadBody errorMessage ->
errorMessage
Run Code Online (Sandbox Code Playgroud)
toString在Elm 0.19中删除。现在有Debug.toString,但不能在生产应用程序中使用(即,当--optimize传递给elm make时,找到后它将失败Debug.toString)