我有三个映射的函数,我希望在捕获异常时停止评估。 我可以捕获异常,但我没有得到我想要的行为。可能是我以不正确的方式思考这个问题(在这种情况下我可能不应该映射一个函数列表),并且会理解这一点。以下是我认为的相关代码。
import qualified Control.Exception as C
data JobException = PreProcessFail
| JobFail
| ChartFail
deriving (Show, Typeable)
instance C.Exception JobException
type ProcessState = MVar ProcessConfig
data ProcessConfig = PConfig { model :: ServerModel
, ipAddress :: String
, cookie :: Cookie
} deriving Show
exceptionHandler :: JobException -> IO ()
exceptionHandler exception = do
writeFile "testException.txt" ("caught exception " ++ (show exception))
-- much more functionality will be put here once I get the logic correct
preProcess :: ProcessState -> IO ()
preProcess sModel = do
putStrLn ("preProcessing" )
initiateJob :: ProcessState -> IO ()
initiateJob sModel = do
C.throw JobFail
putStrLn ("in progress")
makeChart :: ProcessState -> IO ()
makeChart sModel = do
putStrLn ("chart making")
所以现在,当我在ghci中测试这个时,就会发生这种情况。
a <- mapM (flip Control.Exception.catch exceptionHandler) [preProcess world, initiateJob world, makeChart world]
Loading package filepath-1.2.0.0 ... linking ... done.
Loading package unix-2.4.2.0 ... linking ... done.
preProcessing
chart making
我不应该看到字符串“图表制作”。如何在抛出异常时中止对列表的评估?
答案 0 :(得分:4)
mapM
映射函数然后对列表进行排序。所以你在列表中的每个动作周围都有一个catch
。你想要的是将列表排序为单个动作,然后捕获异常一次,从而中断列表中的其他所有内容。以下作品:
(flip Control.Exception.catch exceptionHandler) $ sequence_ [preProcess world, initiateJob world, makeChart world]