Search code examples
elm

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


I am working on an Elm task to decode the JSON from API. The problem I met is the decoder I've written is not matched the JSON so I want to show the error. But I cannot convert the error message from #Http.Error# type to #String# type in Elm with toString function. Here is the code:

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)
                ▔▔▔▔▔▔▔▔

The error was:

NAMING ERROR - I cannot find a toString variable:

168| (Failure (toString errorString), Cmd.none)

I try with Basics.toString but it not work. Can anyone help me to point out the problem?

P/s 1: I am using Elm 0.19

P/s 2: And is there another way to find the problem when decoding the JSON with NoRedInk/elm-decode-pipeline package? I tried with Debug.log but it just printed the function and have no idea how to debug. It's really hard to know where is the problem.


Solution

  • If you're getting back an Http.Error, it will have five possible values:

    type Error
        = BadUrl String
        | Timeout
        | NetworkError
        | BadStatus Int
        | BadBody String
    

    If it's an issue with JSON decoding, it'll be BadBody, and the String will be the error message from the JSON decoder. You might want a function like this:

    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 was removed in Elm 0.19. There is now Debug.toString, but it cannot be used in production applications (i.e. when --optimize is passed to elm make, it will fail when it finds Debug.toString)