如何正确执行涉及异步方法的错误处理

时间:2019-12-20 06:44:30

标签: scala

假设我在Play应用程序中使用的某些服务中定义了以下方法,每个方法都会在失败时执行一些命令,更新数据库并异步发送一些通知。

def thisMightFail(): Future[SomeResult]

def thisUpdatesStatus(): Future[Unit]

def thisSendsNotification(): Future[Unit]

thisUpdatesStatusthisSendsNotification彼此独立,并被要求进行如下所示的错误处理。 (如果失败,则无法进一步执行)

for {
     _ <- Future{ Some process }
result <- thisMightFail() transform {
            case Success(v) => v
            case Failure(cause) => 
                val f = Future.sequence(List(
                thisUpdatesStatus(),
                thisSendsNotification()
             ))
             Failure(new Exception("Command execution failed", cause))
          }
     _ <- Future{ Another process that uses "result" }
             :
} yield ...

我的问题是在返回f之前应该等待Failure(cause)还是在这种情况下有更好的方法来处理错误?

1 个答案:

答案 0 :(得分:0)

  

我的问题是返回失败之前应等待f(原因)   还是有更好的方法来处理这种错误   情况

当前,您的代码无法处理thisUpdatesStatus()thisSendsNotification()的失败。您可以接受这些函数调用的失败吗?
我怀疑如果thisMightFail()失败并且您不更新数据库,那将是不可能的。如果thisMightFail()失败,用户还将收到一些通知。 对于诸如cadence之类的情况,您应该使用工作流平台。您可以找到节奏here的不错介绍。

相关问题