Expressive and composable error types

做~自己de王妃 提交于 2021-02-06 00:48:52

问题


I am struggling with the best way to report errors in a set of functions that should compose nicely, in a library I'm working on.

Concretely, I have functions that look like:

foo, bar, baz :: a -> Maybe a

where foo can fail in only one way (a good fit for Maybe), but bar and baz can fail in two different ways each (good fits for Either BarErrors and Either BazErrors).

One solution is to create:

data AllTheErrors = TheFooError
                  | BarOutOfBeer
                  | BarBurnedDown
                  | ...

and make all the functions return Either AllTheErrors, which expresses the range of errors that might be raised by a composed sequence of these functions at the expense of expressing the range of errors possible for each individual function.

Is there a way I can get both? Maybe with something other than monadic composition? Or with type families (waves hands)...?


回答1:


The Control.Monad.Exception library allows strongly typed exceptions to be used in non IO code. This allows functions to throw errors, and easily compose with functions that throw different errors. For example:

{-# LANGUAGE RankNTypes, MultiParamTypeClasses, FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
import Prelude hiding (catch)
import Control.Monad.Exception


data FooException = FooException deriving (Show, Typeable)
instance Exception FooException

data BarErrors = BarErrors deriving (Show, Typeable)
instance Exception BarErrors

data BazErrors = BazErrors deriving (Show, Typeable)
instance Exception BazErrors

-- sample functions    
foo :: (Throws FooException l) => a -> EM l a
foo a = return a


bar :: (Throws BarErrors l) => a -> EM l a
bar _ = throw BarErrors

baz :: (Throws BazErrors l) => a -> EM l a
baz a = return a


-- using all at once:

allAtOnce :: (Throws FooException l, Throws BarErrors l, Throws BazErrors l) =>
             a -> EM l String
allAtOnce x = do
  _ <- foo x
  _ <- bar x
  _ <- baz x
  return "success!"

-- now running the code, catching the exceptions:

run :: a -> String
run x = runEM $ allAtOnce x `catch` (\(_ :: FooException) -> return "foo failed")
        `catch` (\BarErrors -> return "bar failed")
        `catch` (\BazErrors -> return "baz failed")


-- run 3 results in "bar failed"

See also the papers Explicitly Typed Exceptions for Haskell and An Extensible Dynamically-Typed Hierarchy of Exceptions for more details on using this library.



来源:https://stackoverflow.com/questions/8320855/expressive-and-composable-error-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!