【问题标题】:Calling future in recover partial method [duplicate]在恢复部分方法中调用未来[重复]
【发布时间】:2020-09-13 06:34:37
【问题描述】:

我有部分方法 defaultRecover 帮助从异常中恢复:

  def getName(length: Int): Future[String] = {
    if (length > 0)
      Future.successful("john")
    else
      Future.failed(new RuntimeException("failed"))
  }

  def defaultRecover: PartialFunction[Throwable, String] = {
    case _ => "jane"
  }

  // easy and working
  val res = getName(0) recover {
    defaultRecover
  }

现在的问题。我定义了第二种恢复方法emergencyRecover,我想根据另一个调用的结果选择使用哪种恢复方法-isEmergency()

  def emergencyRecover: PartialFunction[Throwable, String] = {
    case _ => "arnold"
  }

  // simplified - this actually calls REST API
  def isEmergency(): Future[Boolean] = {
    Future.successful(true)
  }

  // type mismatch
  // required: PartialFunction[Throwable,String]
  // found   : Future[PartialFunction[Throwable,String]]
  val res = getName(0) recover {
    isEmergency() map {
      case false => defaultRecover
      case true => emergencyRecover
    }
  }

但是我遇到了类型不匹配。我怎样才能实现这种错误处理?除了恢复,我还需要使用其他方法吗?

【问题讨论】:

    标签: scala future


    【解决方案1】:

    正如我常说的,scaladoc 是你的朋友。您可以使用recoverWith
    另外,请记住它接收部分函数,​​因此您必须执行以下操作:

    val res = getName(0) recoverWith {
      case e => isEmergency() map {
        case false => defaultRecover(e)
        case true  => emergencyRecover(e)
      }
    }
    

    【讨论】:

      【解决方案2】:

      您可以只使用 recoverWith 代替:

        val res2 = getName(0) recoverWith {
          case _ =>  isEmergency().map {
            case false => "jane"
            case true => "arnold"
          }
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-03
        • 2015-06-15
        • 1970-01-01
        • 1970-01-01
        • 2011-03-03
        • 1970-01-01
        相关资源
        最近更新 更多