Haskell IO error handling during I / O operation

In a library, a System.Directoryfunction getPermissionsmay return I / O errors. The documentation states that it may fail with isPermissionErroror isDoesNotExistError. How to handle I / O errors during a call getPermissions?

Attempt:

input <- try (do 
        permissions <- getPermissions filepath 
        print permissions)
case input of
        Left e  -> print "a"
        Right e -> print "b"

Error:

No instance for (Exception e0) arising from a use oftry
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" } }
+4
source share
2 answers

The error message states that it is not possible to determine the type of exception (i.e. the instance Exception) that you want to catch. One possible solution is to provide a type annotation that defines it, as in:

case (input :: Either IOError String) of
    Left e -> print "a"
    Right r -> print "b"

, isDoesNotExistError System.IO.Error, , IOError .

Control.Exception.

+2

( ),

Left e

Left (e :: SomeException)

, ,

input <- try $ getPermissions filepath
case input of
    Left (e :: SomeException) -> print "a"
    Right e -> print "b"

.

0

Source: https://habr.com/ru/post/1537216/


All Articles