Tuesday, March 15, 2016

Handling HTTP Errors in Elm 0.16

Expected knowledge: Basics of Elm and the Elm Architecture

Read to learn: How to handle HTTP errors in Elm

I remember one of the things I struggled with writing my first Elm program (other than writing a JSON decoder) was dealing with non-successful HTTP responses. I've heard the question asked a few times in the Elm Slack channel and decided that I would share how I solved the problem. I'll assume that you're following the Elm Architecture.

Status Quo

Let's start by looking at the signature of the Http.get function:

What we need out of this is an Effects Action to return in our update function. Here's how things might look to start with:

This works great except that we throw away information about the failure case. We either get a Just Response or Nothing!

Retaining Error Information

Let's see how we can do better. First, we need to change our Updated action to account for errors by accepting a Result that can contain either an Error or a Response:

Then we can update our request function to send the errors along as well:

Our update function will need to change as well to accomodate the extra information we're passing along:

This is a big step forward! Now we can update our UI to reflect the fact that something's gone wrong or log the failure to the console.

An Alternative Approach

If we want, though, we can also have a generic error action that we can reuse. Here's what that approach would look like:

Of course, instead of just logging the errors to the console we can show the user an error state, retry, or anything else! I hope this helps but if not, ping me on the Elm slack channel.