在 Elm 0.19 中使用 toString 将 Http.Error 转换为字符串时出错

Error when convert Http.Error to String with toString in Elm 0.19

我正在做一项 Elm 任务,从 API 解码 JSON。我遇到的问题是我写的解码器不匹配 JSON 所以我想显示错误。但是我无法使用 toString 函数将错误消息从 #Http.Error# 类型转换为 #String# 类型的 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)
                ▔▔▔▔▔▔▔▔

错误是:

NAMING ERROR - I cannot find a toString variable:

168| (Failure (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

如果是 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

toString 在 Elm 0.19 中被移除。现在有Debug.toString,但是不能在生产应用中使用(即当--optimize传给elm make,找到Debug.toString就会失败)