简体   繁体   English

Scala期货的异常处理

[英]Exception handling with scala futures

I have a problem with Scala Futures. 我对Scala Futures有问题。 I have a function that takes two parameters: x: Future[Int] and y: Future[Int]. 我有一个带有两个参数的函数:x:Future [Int]和y:Future [Int]。

The function should return a future that completes with: 该函数应返回一个以下列内容完成的将来:

  • value of x if x completes successfully, 如果x成功完成,则x的值,
  • value of y if x fails and y completes successfully, 如果x失败且y成功完成,则y的值,
  • the exception that failed y if x fails and y fails. 如果x失败并且y失败,则失败y的异常。

I cannot seem to figure out how to do this. 我似乎无法弄清楚该如何做。

The code currently: 当前代码:

def myFunction(x: Future[Int], y: Future[Int]): Future[Int] = {
  x.onSuccess {
    case result => return Future(result)
  }
  x.onFailure {
    case e => 
      y.onSuccess {
        case res => return Future(res)
      }
      y.onFailure {
        case f => throw f
      }
  }
}

只是:

x.recoverWith { case _ => y }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM