1

我想在Servant中执行删除操作并返回错误或()。这是我的代码:

del :: Int -> ExceptT ServantErr IO ()
del myId = liftIO $ do
  cn <- getConnection
  a <- execute cn "delete from table1 where id = ?" [myId]
  case a of
    1 -> return ()
    _ -> throwE err503 --compile error

错误是:

  Couldn't match expected type ‘IO ()’
                with actual type ‘ExceptT ServantErr m0 a0’
    In the expression: throwE err503
    In a case alternative: _ -> throwE err503

如果可能的话,我不希望在每个表达式之前使用 liftIO :

del myId =  do
  cn <- liftIO getConnection
  a <- liftIO $ execute cn "delete from table1 where id = ?" [myId]
  case a of
    1 -> return ()
    _ -> throwE err503

那我该如何返回错误呢?

4

1 回答 1

7

我想你将无法避免它。do-block 中的所有内容都必须在同一个 monad 中,因此初始

 del :: Int -> ExceptT ServantErr IO ()
 del myId = liftIO $ do ...

每一行都必须在IO. 但是您可以通过各种方式重新排列事物,例如使用从属 IO 块,其中一些事物聚集在一起:

 del myId = do
   a <- liftIO $ do 
     cn <- getConnection
     execute cn "delete from table1 where id = ?" [myId]
   case a of
     1 -> return ()
     _ -> throwE err503

或者,用Control.Monad.unless说:

del myId = do
  a <- liftIO $ do 
     cn <- getConnection
     execute cn "delete from table1 where id = ?" [myId]
  unless (a == 1) $ throwE err503

和任何数量的其他方式。你没有说你正在使用哪个getConnectionexecute但你确定他们还没有MonadIO m => m ..吗?在这种情况下,你可以放弃liftIO到底?

于 2016-04-04T02:55:24.620 回答