Skip to content

include key in error message from getField functions #44

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 27, 2018
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/Data/Argonaut/Decode/Combinators.purs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Prelude

import Data.Argonaut.Core (Json)
import Data.Argonaut.Decode.Class (class DecodeJson, decodeJson)
import Data.Bifunctor (lmap)
import Data.Either (Either(..))
import Data.Maybe (Maybe(..), fromMaybe, maybe)
import Foreign.Object as FO
Expand All @@ -12,7 +13,7 @@ getField :: forall a. DecodeJson a => FO.Object Json -> String -> Either String
getField o s =
maybe
(Left $ "Expected field " <> show s)
decodeJson
(elaborateFailure s <<< decodeJson)
(FO.lookup s o)

infix 7 getField as .?
Expand All @@ -24,11 +25,17 @@ getFieldOptional o s =
decode
(FO.lookup s o)
where
decode json = Just <$> decodeJson json
decode json = Just <$> (elaborateFailure s <<< decodeJson) json

infix 7 getFieldOptional as .??

defaultField :: forall a. Either String (Maybe a) -> a -> Either String a
defaultField parser default = fromMaybe default <$> parser

infix 6 defaultField as .?=

elaborateFailure :: ∀ a. String -> Either String a -> Either String a
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should make explicit exports for the module so we don't expose this function

elaborateFailure s e =
lmap msg e
where
msg m = "Failed to decode key '" <> s <> "': " <> m