[Haskell-beginners] Catching Network Connection Error

Brent Yorgey byorgey at seas.upenn.edu
Sat May 23 09:56:32 EDT 2009


On Fri, May 22, 2009 at 01:20:39AM -0500, aditya siram wrote:
> Hi all,
> I am trying to Network.HTTP to connect to a website and catch the error if
> the network is down. Here's what I have so far:
> 
> data Errors = DocumentParseError
>             | WebsiteUnreachableError
>             | ISBNNotFoundError
> 
> respHTML' :: ISBN -> IO (Either Errors (IO String))
> respHTML' isbn =
>     do
>       rsp <- simpleHTTP (getRequest $ "
> http://isbndb.com/api/books.xml?results=details&access_key="
>                                         ++ key
>                                         ++ "&index1=isbn&value1="
>                                         ++ isbn :: Request_String)
>       return $ Right $ getResponseBody rsp
>                   `E.catch` (\(e :: E.SomeException ) ->
>                                  return $ Left $ WebsiteUnreachableError)
> 
> I get the following error when I load it into GHCI:
>     Couldn't match expected type `[Char]'
>            against inferred type `Either Errors b'
>       Expected type: IO String
>       Inferred type: IO (Either Errors b)
>     In the expression: return $ Left $ WebsiteUnreachableError
>     In the second argument of `E.catch', namely
>         `(\ (e :: E.SomeException)
>               -> return $ Left $ WebsiteUnreachableError)'
> Failed, modules loaded: none.
> 
> Control.Exception.catch has the following signature :
> catch :: forall a. IO a -> (IOError -> IO a) -> IO a
> 
> I would expect that the handler function needs to return an IO (Either
> Errors (IO String)). Why is it trying to return an IO String?

Because the call to 'catch' only applies to 'getResponseBody rsp',
which is already inside the 'return $ Right $'.  Perhaps you want to
put parentheses around (return $ Right $ getResponseBody rsp) ?

-Brent


More information about the Beginners mailing list