Handling HTTP Errors in Elm 0.16

March 16, 2016 · elm

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:

gist fcbdfd4935e0b88ab693

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:

gist e1172220dfbfd98845e2

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:

gist 9dd14cad30e0a9fae891

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

gist 7892e8076a4fea4006db

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

gist 9a08d89d41e00871a91f

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:

gist d83343901d15b1e8c142

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.