2017-12-17 15 views
0

(1) DB에서 값을 가져 오려는 Action.async가 필요합니다. DB를 사용할 수없는 경우, 다른 자원에 연결을 시도하고 (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을 얻고있다 : 그것은 최선의 방법입니다 ..... 그러나 복구 {} 내부의 문이 형식 불일치 오류가 있는지 확실하지 않다. 내 미래가 실패하면 어떻게 다른 결과를 얻을 수 있습니까?

감사합니다. recoverWith이 결과로 미래를 기대하면서

답변

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

스칼라 Future.recover, 당신 (지도의 아날로그)에 대한 미래에 recoverWith 대신

def recoverWith[U >: T](pf: PartialFunction[Throwable, Future[U]])(implicit executor: ExecutionContext): Future[U] 
관련 문제