How to handle Http errors

143 views
Skip to first unread message

Amitai Burstein

unread,
Sep 2, 2015, 4:19:57 PM9/2/15
to Elm Discuss
I'm practicing my Elm and I've created this simple json fetcher (demo / code).

I was able to get the code that's responsible for fetching the JSON, however I'd be happy to get some help with how to deal with Http errors. I know about Task.toResult, but not sure on how to add it to the existing code.

Basically I'd like to present an on screen debugger with the Http result code (e.g. 200, 404), along with error messages if present.

Ryan Rempel

unread,
Sep 2, 2015, 5:11:12 PM9/2/15
to Elm Discuss
Generally speaking, here's what you might do:

Instead of Task.toMaybe you would call Task.toResult.

Then, your `NewJson` type, instead of this:

NewJson (Maybe (List Item))

would now be something like this:

NewJson (Result Http.Error (List Item))

Then, in your update method, you'd pattern match on NewJson. 

If it's a Result.Ok, then update the items (as you do now), and do something else to the Model which will become apparent in a moment.

If it's a Result.Err, then you would need to be storing the Http.Error in the Model. So, your Model would need that ... it might be a new field, or you might turn isFetching into an ADT that reflects multiple possible status values.

And, of course, the Result.Ok case would now also need to deal with the Http.Error in the Model. (So, the model field might need to be Maybe Http.Error, so you can set it to Nothing when things worked. Or, if you're using a Status ADT, then you'd set the appropriate Status).

Then, in your view, you would need to check for the Http.Error in the model, and then display it somehow.

That's more or less what you'd do -- I'm just writing this off the top of my head, so I may be missing bits.

Ryan Rempel

unread,
Sep 2, 2015, 5:18:05 PM9/2/15
to Elm Discuss
For ADT, read 'union type' -- I forgot to be less cryptic!

Amitai Burstein

unread,
Sep 3, 2015, 2:45:42 AM9/3/15
to elm-d...@googlegroups.com
Perfect, it worked, thanks. Now preparing the blog post :)

--
You received this message because you are subscribed to a topic in the Google Groups "Elm Discuss" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/elm-discuss/oxGPANABg8U/unsubscribe.
To unsubscribe from this group and all its topics, send an email to elm-discuss...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Reply all
Reply to author
Forward
0 new messages