我正在努力寻找报告错误的最佳方法,这些函数应该在我正在处理的库中很好地编写。
具体来说,我的功能如下:
foo, bar, baz :: a -> Maybe a
其中foo
只能以一种方式失败(非常适合Maybe
),但bar
和baz
可能会以两种不同的方式失败(很适合Either BarErrors
和Either BazErrors
)。
一种解决方案是创建:
data AllTheErrors = TheFooError
| BarOutOfBeer
| BarBurnedDown
| ...
并使所有函数返回Either AllTheErrors
,它表示这些函数的组合序列可能引发的错误范围,代价是表示可能的错误范围每个个人功能。
有没有办法可以同时获得两者?也许还有除了monadic组合之外的东西?或者使用类型系列(波浪手)......?
答案 0 :(得分:16)
Control.Monad.Exception库允许在非IO代码中使用强类型异常。这允许函数抛出错误,并且容易构成抛出不同错误的函数。例如:
{-# 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"
有关使用此库的详细信息,另请参阅论文Explicitly Typed Exceptions for Haskell和An Extensible Dynamically-Typed Hierarchy of Exceptions。