Haskell在IO操作期间的错误处理

4
System.Directory库中,getPermissions函数可能会返回IO错误。文档说明可能会失败,其中包括isPermissionErrorisDoesNotExistError。我该如何处理在调用getPermissions时发生的IO错误?
input <- try (do 
        permissions <- getPermissions filepath 
        print permissions)
case input of
        Left e  -> print "a"
        Right e -> print "b"

错误:

No instance for (Exception e0) arising from a use of ‘try’
The type variable ‘e0’ is ambiguous
Note: there are several potential instances:
  instance Exception NestedAtomically
    -- Defined in ‘Control.Exception.Base’
  instance Exception NoMethodError
    -- Defined in ‘Control.Exception.Base’
  instance Exception NonTermination
    -- Defined in ‘Control.Exception.Base’
  ...plus 7 others
In a stmt of a 'do' block:
  input <- try
             (do { permissions <- getPermissions filepath;
                   print permissions })
In the expression:
  do { input <- try
                  (do { permissions <- getPermissions filepath;
                        print permissions });
       case input of {
         Left e -> print "a"
         Right e -> print "b" } }
In an equation for ‘checkwritefilepermissions’:
    checkwritefilepermissions filepath
      = do { input <- try
                        (do { permissions <- getPermissions filepath;
                              print permissions });
             case input of {
               Left e -> print "a"
               Right e -> print "b" } }
2个回答

2
错误消息显示无法确定要捕获的异常类型(即Exception实例)。一种可能的解决方案是提供一个类型注释来指定它,例如:
case (input :: Either IOError String) of
    Left e -> print "a"
    Right r -> print "b"

或者,如果您在System.IO.Error中使用isDoesNotExistError和相关函数来区分错误情况,则异常类型将被推断为IOError,而不需要额外的注释。

有关基本异常捕获实践的相关讨论,请参见Control.Exception文档


0

这个问题有一个简单的解决方法(不是最佳方法),就是替换

Left e

Left (e :: SomeException)

顺便说一下,你的代码可以简化成这样
input <- try $ getPermissions filepath
case input of
    Left (e :: SomeException) -> print "a"
    Right e -> print "b"

你真的应该改进你代码中的那些命名。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接