我想从文件中读取内容,并在左/右使用模式匹配来告诉我说文件存在,如下所示:
tehfile <- readIniFile "somefile_that_does_not_exist.ini"
s <- case tehfile of
Left a -> print "woot"
Right b -> ...
我收到的错误是由Data.Ini库生成的错误:“openFile:不存在(没有这样的文件或目录)”。
理想情况下,我想完全覆盖该文本,或者至少在该库生成的字符串之后附加我的 super 有用的“woot”字符串。我该怎么办?为什么我现在的代码中没有发生?
最佳答案
如果你看看implementation for readIniFile
,那只是
readIniFile :: FilePath -> IO (Either String Ini)
readIniFile = fmap parseIni . T.readFile
首先,它尝试打开并读取文件,然后尝试将内容解析为INI配置。如果文件不存在,则第一部分将失败,并出现异常;第二部分将失败,并显示
Left
。要打印您自己的消息并继续计算,而不是Left
情况下的模式匹配,您需要 catch
异常。λ> import Control.Exception
λ> handler :: IOException -> IO (Either String Ini); handler _ = putStrLn "woot" >> pure (Left "woot")
λ> tehfile <- readIniFile "somefile_that_does_not_exist.ini" `catch` handler
woot
或者您可以使用自己的消息抛出错误以结束计算
λ> handler :: IOException -> IO (Either String Ini); handler _ = error "woot"
λ> tehfile <- readIniFile "somefile_that_does_not_exist.ini" `catch` handler
*** Exception: woot
CallStack (from HasCallStack):
error, called at <interactive>...
或编写自己的异常并抛出该异常
λ> data Woot = Woot deriving (Show)
λ> instance Exception Woot
λ> handler :: IOException -> IO (Either String Ini); handler _ = throwIO Woot
λ> tehfile <- readIniFile "somefile_that_does_not_exist.ini" `catch` handler
*** Exception: Woot
关于haskell - 如何覆盖Haskell中Left上的错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59577203/