1

我正在尝试处理来自我的请求解析器的异常:

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

但是我在使用时遇到了一个问题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))正是我得到的,try因为它的类型是try :: Exception e => IO a -> IO (Either e a),但我得到了Either e a

我错过了什么?

4

2 回答 2

7

try确实产生一个IO (Either e a). 您收到错误消息是因为您将生成的值try与 pattern相匹配Left ex,它的 typeEither a b是 not IO a

要修复您的代码,您需要从(使用或内部)中Either取出,然后对其进行模式匹配。IO>>=<-do

于 2013-05-24T18:17:43.063 回答
5

在 GHC 7.6 及更高版本中,您可以使用

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

如果启用{-# LANGUAGE LambdaCase #-}

于 2013-05-24T18:25:34.997 回答