如何在Haskell中处理这个简单的IO异常 [英] How to handle this simple IO exception in Haskell
问题描述
全部交易:
在下面的代码中, getDirectoryContents dir
可能会失败。例如, dir
可能不存在。如何捕捉并向用户发送有意义的消息?我知道IO异常处理已被多次询问,但我仍然找不到一个简单的方法来做到这一点。
walk :: FilePath - > IO()
walk dir = do
contentsFullPath< - getDirectoryContents dir>> = removeDotFile>> = getFullPath
dirList< - filterM doesDirectoryExist contentsFullPath
fileList< ; - filterM doesFileExist contentsFullPath
forM_ fileList processFile>> forM_ dirList walk
其中
removeDotFile = return。 filter(`notElem` [..,。])
getFullPath = return。 zipWith(< />)(repeat dir)
processFile = getFileSize
您正在寻找模块 Control.Exception
,它有很多捕捉/处理异常的函数,
case
handler :: IOException - >> IO [FilePath]
handler = undefined
walk :: FilePath - > IO()
walk dir = do
contentsFullPath< - 句柄处理程序
getDirectoryContents dir
>> = removeDotFile
>> = getFullPath
...
句柄
与 catch
相同,只是参数被交换。它需要一个 IO
计算,它可能会引发异常,处理某种类型的异常,并运行计算,捕获特定类型的异常。
由于您可能无法返回 FilePath
的适当列表,因此您可能希望更高级地捕获异常,例如 walk dir =句柄处理程序$ do ...
,然后您可以简单地拥有一个类型为 IOException - >的处理程序。 IO()
。
因为在这种情况下,我们感兴趣的是 IO
例外,那是我们用的。
Deal all:
In the below code, getDirectoryContents dir
may fail. For example the dir
might not exists. How to catch this and throw a meaningful message to the user? I know that IO exception handling has been asked many times but i still can't find a simple way to do this.
walk :: FilePath -> IO()
walk dir = do
contentsFullPath <- getDirectoryContents dir >>= removeDotFile >>= getFullPath
dirList <- filterM doesDirectoryExist contentsFullPath
fileList <- filterM doesFileExist contentsFullPath
forM_ fileList processFile >> forM_ dirList walk
where
removeDotFile = return . filter (`notElem` ["..", "."])
getFullPath = return . zipWith ( </> ) (repeat dir)
processFile = getFileSize
You're looking for the module Control.Exception
with it's host of functions for catching/handling exceptions,
in your case
handler :: IOException -> IO [FilePath]
handler = undefined
walk :: FilePath -> IO()
walk dir = do
contentsFullPath <- handle handler $
getDirectoryContents dir
>>= removeDotFile
>>= getFullPath
...
handle
is just the same as catch
except the arguments are swapped. It takes an IO
computation which might throw an exception, a handler for some type of exception, and runs the computation, catching that particular type of exception.
Since you might not be able to return an appropriate list of FilePath
s, you may want to catch the exception higher up, with something more like walk dir = handle handler $ do ...
and then you can simply have a handler of type IOException -> IO ()
.
Since in this case we're interested in IO
exceptions, that what we use.
这篇关于如何在Haskell中处理这个简单的IO异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!