error-or 0.3.0 → 0.3.1
raw patch · 4 files changed
+156/−23 lines, 4 filesdep +error-ordep +tastydep +tasty-hunitdep ~basePVP: major bump suggested
API removals or changes: PVP suggests a major version bump
Dependencies added: error-or, tasty, tasty-hunit
Dependency ranges changed: base
API changes (from Hackage documentation)
- Data.ErrorOr: class ErrorConv t s
+ Data.ErrorOr: class ErrorConv (t :: Type -> Type) (s :: Type -> Type)
Files
- changelog.md +6/−0
- error-or.cabal +23/−9
- src/Data/ErrorOr.hs +75/−14
- tests/Tests.hs +52/−0
changelog.md view
@@ -1,3 +1,9 @@+## 0.3.1 (2026-11-14)+ * Fix `tagIO`: it now tags synchronous exceptions and lets asynchronous ones+ pass unchanged. In 0.3.0 it did the opposite, despite what the changelog said.+ * `prettyErrAcc` indents every line of a multi-line message, not only the first+ * `tagIO` lets `ExitCode` pass unchanged, so `exitWith` inside it still exits+ with the intended code instead of becoming an error ## 0.3.0 (2022-06-16) * tagIO now wraps any non async exception, used to wrap only `IOExceptions` and user errors (from `error` function)
error-or.cabal view
@@ -1,25 +1,22 @@ cabal-version: 1.12 --- This file has been generated from package.yaml by hpack version 0.34.4.+-- This file has been generated from package.yaml by hpack version 0.39.6. -- -- see: https://github.com/sol/hpack------ hash: 941c3da601f16a0d99d2f6eebbe072e40ca00ea145b28ff7cf1057712fe945a5 name: error-or-version: 0.3.0+version: 0.3.1 synopsis: Composable, hierarchical errors. description: An Applicative Functor with error accumulation. Built in tree like error type meant for gathering and reporting errors to users. category: data,library homepage: https://github.com/luntain/error-or-bundle/blob/master/error-or#readme author: Kamil Dworakowski maintainer: kamil@dworakowski.name-copyright: 2020 Kamil Dworakowski license: BSD3 license-file: LICENSE-tested-with:- GHC == 8.0.2 || ==8.2.2 || ==8.6.5 || ==8.8.3 || ==8.10.2 || ==9.0.1 || ==9.2.1 build-type: Simple+tested-with:+ GHC ==8.6.5 || ==8.8.3 || ==8.10.2 || ==9.0.1 || ==9.2.1 || ==9.4.8 || ==9.6.6 || ==9.8.4 || ==9.10.3 || ==9.12.2 extra-source-files: README.md changelog.md@@ -31,10 +28,27 @@ Paths_error_or hs-source-dirs: src- ghc-options: -Wall -fno-warn-name-shadowing+ ghc-options: -Wall -Wunused-packages -fno-warn-name-shadowing build-depends:- base >=4.9 && <5+ base >=4.10 && <5 , containers , mtl+ , text+ default-language: Haskell2010++test-suite error-or-tests+ type: exitcode-stdio-1.0+ main-is: Tests.hs+ other-modules:+ Paths_error_or+ hs-source-dirs:+ tests+ ghc-options: -Wall -Wunused-packages -fno-warn-name-shadowing -Wall -threaded -rtsopts -with-rtsopts=-N+ build-depends:+ base >=4.10 && <5+ , containers+ , error-or+ , tasty+ , tasty-hunit , text default-language: Haskell2010
src/Data/ErrorOr.hs view
@@ -12,10 +12,10 @@ -- | Provides composable and hierarchical errors, with pretty -- printing. The errors are accumulated in a tree like structure,--- 'ErrorAcc'. 'ErrorAcc' is disigned to be read by humans, via+-- 'ErrorAcc'. 'ErrorAcc' is designed to be read by humans, via -- 'prettyErrAcc', not dispatched on by code. Using 'toE' to convert an -- 'ErrorOr' to IO throws (in case it holds an error) a 'PrettyErrAcc'--- that uses 'pretty' in the show instance.+-- that uses 'prettyErrAcc' in the show instance. -- -- This works well for apps where you don't need to display errors in different languages. module Data.ErrorOr@@ -46,8 +46,13 @@ #endif import Control.Monad.Except (MonadError, throwError, catchError) -- it exports GHC.Base.fail (?!) import Data.String+import System.Exit (ExitCode) --- | Use 'Applicative'\'s 'sequenceA' and 'sequenceA_' to compose 'ErrorOr's as opposed to 'Monad' derived functions like 'sequence'.+-- | Compose 'ErrorOr's with 'Applicative' functions ('Data.Foldable.traverse_',+-- 'Data.Foldable.for_', 'Data.Foldable.sequenceA_', '<*>', '*>') to collect all+-- the errors. The 'Monad'-based functions ('mapM_', 'Data.Foldable.forM_',+-- 'sequence_', '>>=', '>>') stop at the first+-- error. See the note on the 'Monad' instance. newtype ErrorOr a = ErrorOr {errorOrToEither :: Either ErrorAcc a} deriving (Show, Read, Eq, Ord, Functor, Foldable, Traversable) @@ -90,13 +95,64 @@ -- | Tag an exception with an annotation. ----- It ignores asynchronous exceptions and has special logic for--- `PrettyErrAcc` for better composition. For `SomeException`, it+-- It lets async exceptions and 'ExitCode' (thrown by 'System.Exit.exitWith'+-- and friends) pass unchanged, and has special logic for+-- `PrettyErrAcc` for better composition. For other exceptions, it -- converts the error message into Text via String and turns it into--- `PrettyErrAcc` tagged with provided adnotation. For `PrettyErrAcc`--- it is streightforward tagging.+-- `PrettyErrAcc` tagged with the provided annotation. For `PrettyErrAcc`+-- it is straightforward tagging. ----- Since ver 0.1.1.0+-- __Use it at boundaries__, where an exception is about to be reported+-- (around @main@, a request handler, a job), not deep inside code whose+-- exceptions someone handles by type. Wrapping erases the type of the+-- original exception, so handlers further up that match a specific type+-- no longer fire. For example, after+--+-- @+-- tagIO \"loading config\" (readFile path) \`catch\` \\(e :: IOException) -> ...+-- @+--+-- the handler never runs, because what escapes is a 'PrettyErrAcc'. The+-- same goes for retry logic keyed on a library's exception type, and for+-- frameworks that use exceptions for control flow (redirects, early+-- responses).+--+-- Whether an exception is asynchronous is decided by its type (whether it+-- is wrapped in 'Exc.SomeAsyncException'), not by how it was delivered:+--+-- * 'Exc.ThreadKilled' (from 'Control.Concurrent.killThread'), the+-- timeout of "System.Timeout", and the @async@ package's+-- @AsyncCancelled@ and @ExceptionInLinkedThread@ are asynchronous and+-- pass through untagged. In particular, a failure of a child that+-- reaches this thread via the @async@ package's @link@ is not tagged,+-- while the same failure observed via @wait@ is.+--+-- * An exception of an ordinary type sent from another thread with+-- 'Control.Concurrent.throwTo' is treated as synchronous and gets+-- wrapped, so a thread that interrupts this one that way cannot catch+-- its own exception type afterwards.+--+-- * Exceptions thrown by the runtime on deadlock+-- ('Exc.BlockedIndefinitelyOnMVar', 'Exc.BlockedIndefinitelyOnSTM',+-- 'Exc.Deadlock') or on @\<\<loop\>\>@ ('Exc.NonTermination') are+-- typed as synchronous and get wrapped.+--+-- Only exceptions raised in the calling thread while the action runs are+-- seen. Failures of threads forked inside the action are not, unless+-- something brings them back (@wait@, @link@, @concurrently@, ...).+--+-- __Alternative on GHC 9.10 and later:__ 'Control.Exception.annotateIO'+-- attaches an annotation to the exception's context without changing its+-- type, so handlers that match by type keep working. The annotations are+-- printed for uncaught exceptions and by 'Exc.displayException' on+-- 'Exc.SomeException' (as checked on GHC 9.10.3), but not by 'show'. They+-- are a flat list rather than a tree like 'ErrorAcc', and they are lost+-- when an exception is caught at its specific type and rethrown with+-- 'Exc.throwIO'. That makes them the better choice for annotating deep+-- inside code; 'tagIO' remains useful at reporting boundaries and on+-- older compilers.+--+-- @since 0.1.1.0 tagIO :: T.Text -> IO a -> IO a tagIO ctx action = action@@ -105,21 +161,26 @@ Just (pretty :: PrettyErrAcc) -> Exc.throwIO $ PrettyErrAcc $ ErrTag ctx (unPrettyErrAcc pretty) Nothing ->- if isAsyncException e- then Exc.throwIO $ PrettyErrAcc $ ErrTag ctx (ErrMessage (T.pack $ show e))- else Exc.throwIO e+ if isAsyncException e || isExitCode e+ then Exc.throwIO e+ else Exc.throwIO $ PrettyErrAcc $ ErrTag ctx (ErrMessage (T.pack $ show e)) where isAsyncException :: Exc.SomeException -> Bool isAsyncException e = case Exc.fromException e of Just (Exc.SomeAsyncException _) -> True Nothing -> False+ isExitCode :: Exc.SomeException -> Bool+ isExitCode e =+ case Exc.fromException e of+ Just (_ :: ExitCode) -> True+ Nothing -> False -- | Pretty print the error. prettyErrAcc :: Int -- ^ Initial indent, usually 0 -> ErrorAcc -> T.Text-prettyErrAcc indent (ErrMessage txt) = T.replicate indent " " <> txt+prettyErrAcc indent (ErrMessage txt) = T.intercalate "\n" . map (T.replicate indent " " <>) . T.splitOn "\n" $ txt prettyErrAcc indent (ErrList errs) = T.intercalate "\n" . map (prettyErrAcc indent) . toList $ errs prettyErrAcc indent (ErrTag str err) = T.intercalate "\n" [prettyErrAcc indent (ErrMessage str), prettyErrAcc (indent + 4) err] @@ -150,7 +211,7 @@ mappend = (<>) mempty = pure mempty --- | OrError's instances for 'Monad' and 'Applicative' don't align,+-- | ErrorOr's instances for 'Monad' and 'Applicative' don't align, -- but the 'Monad' and 'MonadFail' instances are too useful (as in -- convenient) to pass on. -- In particular, composing two failing actions using the@@ -207,7 +268,7 @@ toE Nothing = fail "Nothing" toE (Just a) = pure a --- | Convert from `Either e`, `Left` becomese error.+-- | Convert from `Either e`, `Left` becomes an error. instance Show e => ErrorConv (Either e) ErrorOr where toE (Left err) = fail (show err) toE (Right a) = pure a
+ tests/Tests.hs view
@@ -0,0 +1,52 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+import Control.Concurrent (forkIO, killThread, newEmptyMVar, putMVar, takeMVar, threadDelay)+import Control.Exception+import Data.ErrorOr+import Data.Foldable (traverse_)+import qualified Data.Sequence as Seq+import qualified Data.Text as T+import System.Exit+import Test.Tasty+import Test.Tasty.HUnit++main :: IO ()+main =+ defaultMain $+ testGroup+ "error-or"+ [ testCase "Applicative accumulates errors" $+ (failText "a" *> failText "b" :: ErrorOr ())+ @?= Error (ErrList (Seq.fromList [ErrMessage "a", ErrMessage "b"])),+ testCase "traverse_ accumulates errors" $+ isErrorWith "a\nb" (traverse_ failText ["a", "b"] :: ErrorOr ()),+ testCase "prettyErrAcc indents every line of a message" $+ prettyErrAcc 0 (ErrTag "ctx" (ErrMessage "one\ntwo"))+ @?= "ctx\n one\n two",+ testCase "tagIO tags synchronous exceptions" $ do+ r <- try (tagIO "outer" (tagIO "inner" (throwIO (userError "boom"))))+ case r of+ Left (PrettyErrAcc e) ->+ prettyErrAcc 0 e @?= "outer\n inner\n user error (boom)"+ Right () -> assertFailure "expected an exception",+ testCase "tagIO lets ExitCode through" $ do+ r :: Either ExitCode () <- try (tagIO "ctx" (exitWith (ExitFailure 3)))+ r @?= Left (ExitFailure 3),+ testCase "tagIO lets async exceptions through" $ do+ started <- newEmptyMVar+ result <- newEmptyMVar+ tid <- forkIO $ do+ r <- try (tagIO "ctx" (putMVar started () >> threadDelay 10000000))+ putMVar result r+ takeMVar started+ killThread tid+ r <- takeMVar result+ case r of+ Left (e :: SomeException) ->+ fromException e @?= Just ThreadKilled+ Right () -> assertFailure "expected an exception"+ ]++isErrorWith :: T.Text -> ErrorOr a -> Assertion+isErrorWith expected (Error e) = prettyErrAcc 0 e @?= expected+isErrorWith _ _ = assertFailure "expected an error"