Skip to content

Instantly share code, notes, and snippets.

@simonh1000
Created September 22, 2015 14:10
Show Gist options
  • Save simonh1000/838d0a6997f97adeb81f to your computer and use it in GitHub Desktop.
Save simonh1000/838d0a6997f97adeb81f to your computer and use it in GitHub Desktop.
Elm: Download Json with error handling
import Http
import Markdown
import Html exposing (Html, div, text)
import Task exposing (Task, andThen)
import Json.Decode as Json exposing (..)
type alias ValWithErr = Result String Int
main : Signal Html
main =
Signal.map view readme.signal
-- set up mailbox
-- the signal is piped directly to main
-- the address lets us update the signal
readme : Signal.Mailbox ValWithErr
readme =
Signal.mailbox (Result.Ok 0)
report : ValWithErr -> Task x ()
report val =
Signal.send readme.address val
get : Task Http.Error ValWithErr
get = Http.get dec1 readmeUrl
-- Decoder for get
dec1 : Decoder ValWithErr
dec1 = Json.map Result.Ok ("tag" := int)
-- Error handling specifics
safeGet : Task x ValWithErr
safeGet =
get `Task.onError` (\err -> Task.succeed (errorMapper err))
errorMapper : Http.Error -> ValWithErr
errorMapper err =
case err of
Http.UnexpectedPayload s -> Result.Err s
otherwise -> Result.Err "http error"
-- VIEW
view : ValWithErr -> Html
view msg =
case msg of
Result.Ok i -> div [] [ text <| toString i ]
Result.Err m -> div [] [ text m ]
-- get the readme *and then* send the result to our mailbox
port fetchReadme : Task Http.Error ()
port fetchReadme =
safeGet `Task.andThen` report
-- the URL of Json
-- {"tag": 123} or {"tag": 1x23}
readmeUrl : String
readmeUrl =
"http://127.0.0.1:5000/micro.json"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment