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?
Use HttpResponse. getStatusLine() , which returns a StatusLine object containing the status code, protocol version and "reason".
Sometimes when you try to visit a web page, you're met with an HTTP error message. It's a message from the web server that something went wrong. In some cases it could be a mistake you made, but often, it's the site's fault.
Try refreshing the page, occasionally a simple reload will solve the conundrum. If this doesn't work, try clearing your browser cookies and cache. If you are finding this error on your website, the solutions are much different. Contact your content management system or webmaster for more help.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With