Last active
May 11, 2023 21:12
-
-
Save pete-murphy/dfd3a952a608e416a35921ff408df4e4 to your computer and use it in GitHub Desktop.
Unify error types in a simple fetch & decode example (PureScript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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