我想要一个Action.async,它(1)尝试从数据库中获取值。如果数据库不可用,它将尝试连接到另一个资源,并(2)从那里获取值。因为我使用的两个资源返回Future,我将它们与“recover”关键字分开。我不确定它是否是最好的方法.....但是恢复{}中的语句有类型不匹配错误:
def show(url: String) = Action.async { implicit request: Request[AnyContent] =>
println("url: " + url)
val repositoryUrl = RepositoryUrl(url)
val repositoryId = RepositoryId.createFromUrl(url)
// Listing commits from the DB
val f: Future[Seq[Commit]] = commit.listByRepository(repositoryId.toString())
f.map { f: Seq[Commit] =>
val json = JsObject(Seq(
"project URL" -> JsString(url),
"list of commits" -> Json.toJson(f)))
Ok(json)
}.recover {
case e: scala.concurrent.TimeoutException =>
// InternalServerError("timeout")
// Listing commits from the Git CLI
val github = rules.GitHub(repositoryUrl)
val seq: Future[Seq[Commit]] = github.listCommits
seq.map { seq: Seq[Commit] =>
val json = JsObject(Seq(
"project URL" -> JsString(url),
"list of commits" -> Json.toJson(seq)))
Ok(json)
}
}
}
我在type mismatch; found : scala.concurrent.Future[play.api.mvc.Result] required: play.api.mvc.Result
行上收到错误seq.map { seq: Seq[Commit] =>
。如果我未来失败,我该如何返回另一个结果呢?
谢谢!
答案 0 :(得分:2)
recover
在Future中包含普通结果(类似于map),而recoverWith
期望Future作为结果(类似于flatMap)。 (https://stackoverflow.com/a/36585703/5794617)。因此,您应该使用recoverWith
:
def show(url: String): EssentialAction = Action.async { implicit request: Request[AnyContent] =>
// This future will throw ArithmeticException because of division to zero
val f: Future[Seq[Int]] = Future.successful(Seq[Int](1, 2, 3, 4 / 0))
val fResult: Future[JsObject] = f.map { r =>
JsObject(Seq(
"project URL" -> JsString(url),
"list of commits" -> Json.toJson(r)))
}.recoverWith {
case e: ArithmeticException =>
val seq: Future[Seq[Int]] = Future.successful(Seq(1, 2, 3, 4))
seq.map { seq: Seq[Int] =>
JsObject(Seq(
"project URL" -> JsString(url),
"list of commits" -> Json.toJson(seq)))
}
}
fResult.map { r =>
Ok(r)
}
}
答案 1 :(得分:0)
Scala Future.recover
的签名为
def recover[U >: T](pf: PartialFunction[Throwable, U])(implicit executor: ExecutionContext): Future[U]
尝试使用recoverWith
代替
def recoverWith[U >: T](pf: PartialFunction[Throwable, Future[U]])(implicit executor: ExecutionContext): Future[U]