Return Future fail when Option has None

419 Views Asked by At

I have below code which works fine

case class MainRequest(optionalVal: Option[String])

case class IntermediateResult(someVal: String)

case class FinalResult(param: String)

def process(param: String, intermediateResult: IntermediateResult): Option[String] = ???

def getFutureOfList: Future[List[Int]] = ???

def getFutureOfOption(param: Int): Future[Option[IntermediateResult]] = ???

def overallResult(mainReq: MainRequest): Future[Option[FinalResult]] = {
  (for {
    optionalOne <- OptionT(getFutureOfList.map(_.headOption))
    optionalTwo <- OptionT(getFutureOfOption(optionalOne))
  } yield {
    mainReq.optionalVal.flatMap(process(_, optionalTwo)).map(FinalResult)
  }).value.map(_.flatten)
}

But now , I need to change overallResult function so that it would return Future fail Exception when mainReq.optionalVal is None or process(_,optionalTwo) results in None. As much as possible, trying not to change the return type of function.

I tried below but can't fail future inside yield.

def overallResult(mainReq: MainRequest): Future[Option[FinalResult]] = {
  (for {
    optionalOne <- OptionT(getFutureOfList.map(_.headOption))
    optionalTwo <- OptionT(getFutureOfOption(optionalOne))
  } yield {
    mainReq.optionalVal match {
      case Some(contains) =>
        process(contains, optionalTwo) match {
          case Some(result) => FinalResult(result)
          case None => new RuntimeException("process(contains, optionalTwo) resulted in None")
        }
      case None => new RuntimeException("mainReq.optionalVal resulted in None")
    }}).value.map(_.flatten)
0

There are 0 best solutions below