Commits

Michael Snoyman  committed 8216c04

modifyFailure (bos/aeson#104)

  • Participants
  • Parent commits a41f668

Comments (0)

Files changed (3)

File Data/Aeson/Types.hs

     , parseEither
     , parseMaybe
     , ToJSON(..)
+    , modifyFailure
 
     -- * Inspecting @'Value's@
     , withObject

File Data/Aeson/Types/Internal.hs

     , parse
     , parseEither
     , parseMaybe
+    , modifyFailure
     -- * Constructors and accessors
     , object
     ) where
 object :: [Pair] -> Value
 object = Object . H.fromList
 {-# INLINE object #-}
+
+-- | If the inner @Parser@ failed, modify the failure message using the
+-- provided function. This allows you to create more meaningful error messages.
+-- For example:
+--
+-- > parseJSON (Object o) = modifyFailure
+-- >     ("Parsing of the Foo value failed: " ++)
+-- >     (Foo <$> o .: "someField")
+--
+-- Since 0.6.2.0
+modifyFailure :: (String -> String) -> Parser a -> Parser a
+modifyFailure f (Parser p) =
+    Parser $ \failure success -> p (modifyFailure' failure) success
+  where
+    modifyFailure' failure original = failure $ f original

File tests/Properties.hs

 regress_gh72 ys = G.decode (G.encode m) == Just m
     where m = Map.fromList ys
 
+modifyFailureProp :: String -> String -> Bool
+modifyFailureProp orig added =
+    result == Error (added ++ orig)
+  where
+    parser = const $ modifyFailure (added ++) $ fail orig
+    result :: Result ()
+    result = parse parser ()
+
 data Foo = Foo {
       fooInt :: Int
     , fooDouble :: Double
     ],
   testGroup "genericToFromJSON" [
       testProperty "_UFoo" (genericToFromJSON :: UFoo -> Bool)
+    ],
+  testGroup "failure messages" [
+      testProperty "modify failure" modifyFailureProp
     ]
   ]