Skip to content

Instantly share code, notes, and snippets.

@pete-murphy
Last active May 11, 2023 21:12
Show Gist options
  • Select an option

  • Save pete-murphy/dfd3a952a608e416a35921ff408df4e4 to your computer and use it in GitHub Desktop.

Select an option

Save pete-murphy/dfd3a952a608e416a35921ff408df4e4 to your computer and use it in GitHub Desktop.
Unify error types in a simple fetch & decode example (PureScript)
module Main where
import Prelude
import Affjax as Affjax
import Affjax.ResponseFormat as ResponseFormat
import Control.Monad.Except (ExceptT(..))
import Control.Monad.Except as Except
import Data.Argonaut as Argonaut
import Effect (Effect)
import Effect.Class as Effect
import Effect.Aff (Aff)
import Effect.Aff as Aff
import TryPureScript (h1, p, text, render, code)
type Todo
= { userId :: Int
, id :: Int
, title :: String
, completed :: Boolean
}
data AppError
= FetchError Affjax.Error
| DecodeError Argonaut.JsonDecodeError
instance Show AppError where
show = renderAppError
renderAppError :: AppError -> String
renderAppError = case _ of
FetchError err -> Affjax.printError err
DecodeError err -> show err
fetchTodo :: ExceptT AppError Aff Todo
fetchTodo = do
let url = "https://jsonplaceholder.typicode.com/todos/1"
response <- Except.withExceptT FetchError
(ExceptT (Affjax.get ResponseFormat.json url))
Except.withExceptT DecodeError
(Except.except (Argonaut.decodeJson response.body))
main :: Effect Unit
main = Aff.launchAff_ do
todo <- Except.runExceptT fetchTodo
Effect.liftEffect do
let html = h1 (text "Try PureScript!") <> p (code (text (show todo)))
render html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment