Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the error message out of Http.Error?

Tags:

elm

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?

like image 938
Martimatix Avatar asked May 23 '16 12:05

Martimatix


People also ask

How can I get error code from HTTP response?

Use HttpResponse. getStatusLine() , which returns a StatusLine object containing the status code, protocol version and "reason".

What does it mean when it says HTTP error?

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.

How do I fix HTTP problems?

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.


1 Answers

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)
like image 89
Chad Gilbert Avatar answered Oct 04 '22 14:10

Chad Gilbert