haskell - 如何覆盖Haskell中Left上的错误消息?

标签 haskell error-handling pattern-matching

我想从文件中读取内容,并在左/右使用模式匹配来告诉我说文件存在,如下所示:

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/

相关文章:

json - 来自 Haskell 的查询请求,包含 "same data"的两倍

haskell - 由于 regex-tdfa-text-1.0.0.2,leksah 安装失败

haskell - 在 IO 中运行分布式进程的 Process 类型

PHP 使用自定义异常处理程序捕获未捕获异常

sql - 在忽略大小写和特殊字符的两列中查找可能的重复项

haskell - 在haskell中foreach的初学者/学习者实现

algorithm - 以随机顺序嵌套调用

python - Python nmap portscanner错误

php - 自定义404 ErrorDocument路径在htaccess中不起作用

functional-programming - OCaml "with"保护模式匹配