本文介绍了在runDb中的MaybeT和事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 对于我之前关于链接失败的问题,Michael Snoyman曾建议我使用 MaybeT 来运行它们,以防其中任何一个失败时,它会短路到没有。 我在印象之下 runDb 在事务中运行一切。所以不应该在代码中的任何一点失败自动回滚交易? mauth< - runDb $ runMaybeT $ do 有效< - MaybeT $ return $ listToMaybe errs uid< - MaybeT $ insertUnique u vid< - MaybeT $ getBy $ UniqueField v - 此步骤失败,但以前的插入操作不会执行back auth< - liftIO $ createAuthToken uid return auth 当我运行上面的代码, getBy 失败,但用户仍然被插入。我误解 runDb 会在 MaybeT Nothing >?我是否需要使用其他一些Monad来运行? $ b 更新:欣赏您对如何以最佳方式回滚失败的想法。 这是我根据迈克尔的建议最终做的。 mauth valid 案例ma 只是_ - >返回ma Nothing - > liftIO $ throwIO MyException 现在我需要弄清楚如何很好地捕捉这个异常并返回一个合适的错误信息。 谢谢! 你需要为Persistent抛出一个运行时异常(通过像 throwIO 之类的东西),以将其视为回滚情况。 For my previous question on chaining failures, Michael Snoyman had suggested I use MaybeT to run them so if any of them fails, it will just short-circuit to Nothing. I was under the impression runDb runs everything in a transaction. So shouldn't a failure at any point in code automatically rollback the transaction?mauth <- runDb $ runMaybeT $ do valid <- MaybeT $ return $ listToMaybe errs uid <- MaybeT $ insertUnique u vid <- MaybeT $ getBy $ UniqueField v -- this step fails but previous insert does not roll back auth <- liftIO $ createAuthToken uid return authWhen I run the above code, the getBy fails but user was still inserted. Am I misunderstanding that runDb will rollback on a Nothing inside MaybeT? Do I need to use some other Monad for this to work? Appreciate your thoughts on how to best rollback on failure.Update: This is what I ended up doing per Michael's suggestion. mauth <- runDb $ do ma <- runMaybeT $ do valid <- ... case ma of Just _ -> return ma Nothing -> liftIO $ throwIO MyExceptionNow I need to figure out how to catch this exception nicely outside and return a proper error message back.Thanks! 解决方案 Returning Nothing is not the same thing as a failure. You'd need to throw a runtime exception (via something like throwIO) for Persistent to treat it as a rollback situation. 这篇关于在runDb中的MaybeT和事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-16 09:03