我正在嘗試手動處理檔案錯誤,以便可以列印自己的訊息,目前我有以下代碼:
handleFileError :: FileError -> IO a
handleFileError (FileError errorKind) = do
case errorKind of
NotFound -> undefined
NoPermission -> undefined
IsDirectory -> undefined
fileRead :: String -> IO String
fileRead file = do
pathExists <- doesPathExist file
notDirectory <- doesFileExist file
-- These two must be handled before `System.Directory.getPermissions` is called
-- or else it will error.
permissions <- getPermissions file
let hasReadPermissions = readable permissions
if hasReadPermissions then undefined -- This is the success case
else handleFileError $ FileError NoPermissions
我想檢查 3 個布林值(pathExists、notDirectory 和 hasReadPermissions)中的任何一個是否為假,然后采取相應措施。我嘗試使用帶有 的案例來實作這一點False,但這總是運行第一個分支。
uj5u.com熱心網友回復:
一種方法是使用MultiWayIf:
do
pathExists <- doesPathExist file
notDirectory <- doesFileExist file
permissions <- unsafeInterleaveIO (getPermissions file)
if
| not pathExists -> -- ...
| not notDirectory -> -- ...
| not permissions -> -- ...
| otherwise -> -- ...
如果您對擴展程式過敏,獲得此功能的老式方法是使用守衛,如:
case () of
_ | not pathExists -> -- ...
| not notDirectory -> -- ...
| not permissions -> -- ...
| otherwise -> -- ...
但我不推薦這些。相反,只需對檔案做一些事情,然后捕獲例外;否則,在檢查和檔案使用之間會出現檔案系統從您下面更改的競爭條件。像這樣:
fileRead :: String -> IO String
fileRead = catch (undefined {- success case -}) $ \e -> if
| isDoesNotExistError e -> -- ...
| isPermissionError e -> -- ...
| otherwise -> throw e
uj5u.com熱心網友回復:
我已經解決了這個問題 - 我沒有意識到可以以if其他語言中的 else-if 類似的方式嵌套陳述句:
if not (pathExists) then handleFileError $ FileError NotFound
else if not (notDirectory) then handleFileError $ FileError IsDirectory
else do
permissions <- getPermissions file
let hasReadPermissions = readable permissions
if hasReadPermissions then undefined -- success
else handleFileERror $ FileError NoPermissions
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528527.html
