Skip to content

Instantly share code, notes, and snippets.

@simonh1000
Created September 23, 2015 08:06
Show Gist options
  • Save simonh1000/dfcfd018952142497817 to your computer and use it in GitHub Desktop.
Save simonh1000/dfcfd018952142497817 to your computer and use it in GitHub Desktop.
Elm architecture example with Http (Json parsing) error handling
module ArchictectureErrorHandler where
import Text exposing (fromString)
import String
import Json.Decode as Json exposing (..)
import StartApp exposing (start)
import Html exposing (..)
import Http exposing (get, Error)
import Effects exposing (Effects)
import Task exposing (..)
-- MODEL
type alias Model = Result Http.Error Int
type Action =
Persistant Model
-- INIT
init : (Model, Effects Action)
init = (Ok 0, loadData)
-- ASYNC EFFECTS
dec1 : Decoder Int
dec1 = "tag" := int
-- microJson = {"tag": 1x23}
getData : Task Http.Error Int
getData = Http.get dec1 "http://127.0.0.1:5000/micro.json"
-- map : (a -> b) -> Task x a -> Task x b
-- Effects.task : Task Never a -> Effects a
loadData : Effects Action
loadData =
getData
|> Task.toResult -- Task y (Result Http.Error Int)
|> Task.map Persistant -- Task y Action
|> Effects.task -- Effects Action
-- UPDATE
update : Action -> Model -> (Model, Effects Action)
update act model =
let (Persistant newmodel) = act
in (newmodel, Effects.none)
-- VIEW
view : Signal.Address Action -> Model -> Html
view address model =
case model of
Result.Ok i -> div [] [ text <| toString i ]
Result.Err m -> div [] [ text <| errorMapper m ]
errorMapper : Http.Error -> String
errorMapper err =
case err of
Http.UnexpectedPayload s -> s
otherwise -> "http error"
-- START APP
app =
start
{ init = init
, update = update
, view = view
, inputs = []
}
main =
app.html
port tasks : Signal (Task.Task Effects.Never ())
port tasks =
app.tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment