2017-12-17 21 views
0

(1)DBから値を取得しようとするAction.asyncが必要です。 DBが利用できない場合、別のリソースに接続しようとし、(2)そこから値を取得します。私が使用している2つのリソースがFutureを返すので、私は "recover"キーワードでそれらを分離しています。私はそれが最善の方法であるかどうかわからないです.....しかし、回復{}内の文は、型の不一致エラーがあります。scala.concurrent.Future [play.api.mvc.Result] required:play.api.mvc.Result

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) 
     } 
    } 
    } 

私はラインseq.map { seq: Seq[Commit] =>にエラーtype mismatch; found : scala.concurrent.Future[play.api.mvc.Result] required: play.api.mvc.Resultを取得しています。私の未来から失敗した場合、どうすれば別の結果を返すことができますか?

ありがとうございます!

答えて

1

recoverは、(マップのアナログ)あなたのための未来でプレーンな結果をラップ使用してみてください

def recover[U >: T](pf: PartialFunction[Throwable, U])(implicit executor: ExecutionContext): Future[U] 

の署名を持っています(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) 
    } 
} 
0

ScalaのFuture.recoverrecoverWithが、結果として将来を期待しながら、recoverWith代わり

def recoverWith[U >: T](pf: PartialFunction[Throwable, Future[U]])(implicit executor: ExecutionContext): Future[U] 
関連する問題