【问题标题】:recover future is not responding as expected (scala)恢复未来没有按预期响应(scala)
【发布时间】:2018-08-24 00:38:45
【问题描述】:

我有一个自定义案例类异常:

 case class RecordNotFoundException(msg: String) extends RuntimeException(msg)

在我的 dao 中,我有一个从数据库中提取对象的方法,它返回未来,如果这个未来失败,我会抛出 RecordNotFoundException 异常:

  def getPerson(personId: String): Future[Person] = {
    val q = quote {
      query[Person].filter(per => per.personId == lift(personId))
    }
    ctx.run.map(_.head) recover {
      case ex: NoSuchElementException => throw RecordNotFoundException(s"personId $personId does not exist")
    }
  }

在另一种方法中,我调用了 getPerson 方法,因此我将恢复添加到另一种方法中,并且我想在未来因 RecordNotFoundException 失败时返回一些内容:

def run(personDao: PersonDao): Future[String] = {
  if (true) {
    for {
      person <- personDao.getPerson("some_user_id")
      something <- someOtherFuture
    } yield {
      // what happens here not relevant
    }
  } else {
    Future.successful("got to the else")
  } recover {
    case e: RecordNotFoundException => "got to the recover"
  }
}

所以基本上我希望 run() 方法在 getPerson 失败时返回“得到恢复”,但由于某种原因我没有得到恢复……失败回到控制器。

请问有人知道这是为什么吗?

【问题讨论】:

  • recover 不应该抛出,它应该返回一个值。也许你想要 recoverWith。

标签: scala playframework


【解决方案1】:

首先看看你的recover 在哪里。为什么不把它移到方法的最后一行呢?类似的东西:

def getPerson(id: String): Future[String] = Future("Andy")
def someOtherFuture(id: String) = Future("Mandy")

case class RecordNotFoundException(msg: String) extends RuntimeException(msg)

def run(personDao: String): Future[String] = {
  if (true) 
    for {
      person <- getPerson("some_user_id")
      something <- someOtherFuture("1")
    } yield {
      person
    }
  else Future.successful("got to the else")
}recover { case e: RecordNotFoundException => "got to the recover"}

同时将recover 移动为getPerson

在我看来,在您的模型和/或服务中使用 Future/recover 并没有错,然后异常会返回到控制器。然后控制器方法处理自定义的异常;并将InternalServerErrorBadRequest 返回给用户或API 调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 2019-11-26
    • 2012-01-14
    • 2019-12-01
    相关资源
    最近更新 更多