捕获异常后如何停止评估函数列表



我映射了三个函数,我希望在捕获异常时停止求值。我可以捕获异常,但没有得到我想要的行为。可能是我考虑这个问题的方式不正确(也许在这种情况下我不应该映射函数列表),如果有人指出这一点,我将不胜感激。以下是我认为相关的代码。

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

我不应该看到字符串"chart making"。如何在抛出异常时中止对列表的求值?

mapM映射函数,然后排序列表。所以你在列表中的每个动作周围都有一个catch。您需要的是将列表排序为单个操作,然后捕获异常一次,从而中断列表中的其他所有内容。以下作品:

(flip Control.Exception.catch exceptionHandler) $ sequence_ [preProcess world, initiateJob world, makeChart world]

最新更新