【问题标题】:Returning Future[Int] from Future[Option[Int]] with support of Failing the future从 Future[Option[Int]] 返回 Future[Int] 并支持 Failing the future
【发布时间】:2017-09-24 17:35:24
【问题描述】:

我有下面的代码块。我的意图是使用方法参数进行一些处理并返回Future[Int] 或fail Future。如果我对Future 中的方法的参数是None 类型,我想使Future 失败。我有下面的代码。我想知道是否有更简洁和实用的方法来实现同样的目标。

def testoption(myFutOptInt: Future[Option[Int]]) = {
    myFutOptInt.map { myOptInt =>
      myOptInt match {
        case None => throw new BadRequestException("Oh no.....") //Future.failed(BadRequestException(""))
        case Some(myInt) => myInt + 45
      }
    } recoverWith {
      case e:Exception => Future.failed(e)
    }
  }
  • 我不喜欢我必须进行比赛的部分,想知道是否有办法进行map 或更好的方法并且仍然可以实现它。如果我做getOrElse,我想如果值不是None,我将无法编写业务逻辑?所以我认为getOrElse 也不可能?
  • 我不喜欢这段代码的另一件事是我抛出了一个异常,然后我必须执行recoverWith 才能使Future 失败。

我可以如何增强上面的代码?

【问题讨论】:

    标签: scala functional-programming scala-collections


    【解决方案1】:

    如果你特别需要BadRequestException,这就够了:

    def testoption(myFutOptInt: Future[Option[Int]]) =
      myFutOptInt.map { 
        case None => throw new BadRequestException("Oh no.....") 
        case Some(myInt) => myInt + 45
      }
    

    如果你不关心特定的错误类型,你可以更进一步:

    def testoption(myFutOptInt: Future[Option[Int]]) = myFutOptInt.map(_.get + 45)
    

    如果没有价值,这会给你java.util.NoSuchElementException: None.get


    recoverWith 绝对是多余的 b/c 如果在 map 内抛出异常,整个操作会导致 Future 失败。对于大多数(如果不是全部)Future 方法来说都是如此。

    对于匹配,您可以使用opt.fold(throw ...)(...) 或.map(...).getOrElse(throw ...) 来避免它,但我认为这些选项的可读性较差。我建议只使用模式匹配函数定义来减少额外的代码

    【讨论】:

    • 我正在编写这个方法,说它被用作服务,我想将 Future.failed 返回给 REST 控制器。对于那个用例,你会说我可以避免使用Future.failed and recoverWith?
    • @curiousengineer 用例无关紧要。如果map 中的函数抛出,则生成的Future 会自动失败,您无需执行任何其他操作。你的recoverWith 代码本质上是一个空操作。
    • 我想我明白了。如果不总是有时,recoverWith 的全部意义就是说如果我得到Exception of type so and so,请尝试恢复这样做等等。在这里,无论如何,我只是在 recoverWith 中失败了,正如你所说的那样,它会因抛出而失败。对吗?
    • @curiousengineer 是的。你只是总是再次失败。
    猜你喜欢
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2016-11-08
    • 2019-08-12
    • 1970-01-01
    • 2016-08-01
    • 2019-01-13
    相关资源
    最近更新 更多