13

I'm attempting to complete an exercise in the Elm 0.17 tutorial for HTTP. If fetching a gif fails, I would like to let the user know why it failed with an error message.

I've modified my model to be:

type alias Model =
  { topic : String
  , gifUrl : String
  , errorMessage : String
  }

And fetch fail in update to be:

FetchFail error ->
  (Model model.topic model.gifUrl (errorMessage error), Cmd.none)

Where the function errorMessage is as follows:

errorMessage : Http.Error -> String
errorMessage error =
  case error of
    Http.Timeout ->
      "Timeout"
    Http.NetworkError  ->
      "Network Error"
    Http.UnexpectedPayload _ ->
      "UnexpectedPayload"
    Http.BadResponse _ _ ->
      "BadResponse"

The above function seems like unnecessary boiler plate to me. Is there a way that I can directly convert Http.Error into a string?

Martimatix
  • 1,553
  • 1
  • 15
  • 18

1 Answers1

15

You can convert anything to a string using toString. That will give you nearly the same output as your case statements:

toString Timeout == "Timeout"
toString NetworkError == "NetworkError"
toString (UnexpectedPayload "Error") == "UnexpectedPayload \"Error\"" 
toString (BadResponse 500 "Error") == "BadResponse 500 \"Error\""

Just replace the call to errorMessage with toString and you can get rid of errorMessage entirely:

FetchFail error ->
  (Model model.topic model.gifUrl (toString error), Cmd.none)
Chad Gilbert
  • 36,115
  • 4
  • 89
  • 97
  • 1
    If the response was a `BadResponse 400 """{"errors": ["missing required argument q"]"""`, the boilerplate @Martimatix used will be required, no? In essence, the response would is an `Either Error a`. – François Beausoleil May 30 '16 at 12:00
  • 2
    If you wanted to omit the parameters and just print "BadResponse", then yes, you would have to explicitly call that out in a case statement, and you could have an underscore catch-all case that then defaults to `toString`. – Chad Gilbert May 30 '16 at 15:17
  • `toString` was changed to the `Debug` module as of version 0.19. – Gonzalo Jul 08 '19 at 03:17