代码之家  ›  专栏  ›  技术社区  ›  JohnBigs

恢复未来未按预期响应(scala)

  •  0
  • JohnBigs  · 技术社区  · 6 年前

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

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

    在DAO中,我有一个从数据库中提取对象的方法,它返回future,如果future失败,我将抛出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方法,因此我将recover添加到了另一个方法中,并希望在将来失败时返回一些内容,并返回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"
      }
    }
    

    所以基本上,当getPerson失败时,我希望run()方法返回“got to the recover”,但是由于某种原因,我没有得到recover…失败会返回到控制器。

    有人知道为什么吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   o-0    6 年前

    首先看看你的 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"}
    

    也移动 恢复 对于 getPerson 也。

    在我看来,使用 Future/recover 在您的模型和/或服务中,然后异常返回到控制器。然后,controller方法处理定制的异常;并返回 InternalServerError BadRequest 对用户或API调用。