Joe Hillenbrand
Joe Hillenbrand

Reputation: 875

try is returning Either instead of IO (Either ex a)

I'm trying to handle exceptions from my request parser:

   go bs =                                                                 
       case try $ parseRequest reader bs secure of                             
         Left  ex             -> exceptionHandler writer ex                 
         Right (request, bs') -> do                                         
            sendResponse writer =<< app request                             
            go bs'                                                               

But I have an issue when using try:

Couldn't match expected type `IO (Either e0 (Request, ByteString))'
            with actual type `Either t0 t1'
In the pattern: Left ex
In a case alternative: Left ex -> exceptionHandler writer ex
In the expression:
  case try $ parseRequest reader bs secure of {
    Left ex -> exceptionHandler writer ex
    Right (request, bs')
      -> do { sendResponse writer =<< app request;
              go bs' } }

IO (Either e0 (Request, ByteString)) is exactly what I except to get from try because its type is try :: Exception e => IO a -> IO (Either e a), but instead I get Either e a.

What am I missing?

Upvotes: 1

Views: 173

Answers (2)

luqui
luqui

Reputation: 60463

In GHC 7.6 and later, you can use

try (parseRequest reader bs secure) >>= \case
    Left ex -> ...
    Right (request, bs') -> ...

If you enable {-# LANGUAGE LambdaCase #-}

Upvotes: 5

sepp2k
sepp2k

Reputation: 370212

try does produce an IO (Either e a). You're getting the error message because you're matching the value produced by try against the pattern Left ex, which has the type Either a b, not IO a.

To fix your code, you'd need to get the Either out of the IO (using >>= or <- inside do) and then pattern match against that.

Upvotes: 7

Related Questions