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

旧城冷巷雨未停 提交于 2019-12-24 07:17:19

问题


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?


回答1:


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.




回答2:


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 #-}



来源:https://stackoverflow.com/questions/16741139/try-is-returning-either-instead-of-io-either-ex-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!