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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments