| Safe Haskell | None |
|---|---|
| Language | Haskell2010 |
Data.Aeson.Commit
Description
Commitment mechanism for aeson Parser.
This is comes up when you e.g. want to make a distinction between in error handling for missing keys and malformed keys.
As an example, this parser will yield nested.value if there the key nested is present, and value if it is not present.
parse o = (o .:> "nested") (withObject "nestedObj" (.: "value"))
<|> tryParser (o .: "value"){ value: "foo", otherField: "bar" }
-> Right "foo"
{ value: "foo", nested: { value: "bar" } }
-> Right "bar"
{ value: "foo", nested: { bar: 9 } }
-> Left "Error in $.nested: key \"value\" not found"
{ value: "foo", nested: 9 }
-> Left "Error in $.nested: parsing nestedObj failed, expected Object, but encountered Number"
{}
-> Left
"Error in $: No match,
- key \"value\" not found"
- key \"nested\" not found"Documentation
commit :: Parser a -> (a -> Parser b) -> Commit b Source #
Construct a commit.
If the first parser succeeds, the Commit is a success, and any failures in the inner action will be preserved.
tryParser :: Parser a -> Commit a Source #
Turn a Parser into a Commit
Unlike liftParser, the parser's failure is recoverable.
tryParser empty <|> p = p
liftParser :: Parser a -> Commit a Source #
A Parser that has _two_ failure modes; recoverable and non-recoverable.
The default, recoverable failure is the equivalent to aeson's default Parser behavior.
The non-recoverable failure mode is used to commit to a branch; to commit means that every subsequent failure is non-recoverable.
You turn a commit back into a normal Parser using runCommit.
As an additional benefit, if no commit succeeded the parser error message will contain all encountered errors.
The implementation works by capturing failure in either the ExceptT or in the underlying Parser.
The derived Alternative instance will only recover from failures in the ExceptT.
This means that as soon as we successfully construct a Right value, the Alternative considers the Commit a success, even though the underlying parser might have failed.
The Void represents the guarantee that we only collect error values.