2016-10-25 3 views
0

例外を捕捉して、次のコードでカスタムページにリダイレクトしたいと思います。しかし、例外は捕捉されていません。Play2.5/scalaコントローラのハンドル例外

def addItemWithParts(item: Item, parts: Seq[String]): Future[Int] = { 
    ... // May throw exceptions 
} 

def handleAddItem = auth.SecuredAction.async { implicit request => 
    itemForm.bindFromRequest.fold(
    formWithErrors => { 
     Future.successful(
     Redirect(controllers.www.routes.ItemController.startAddItem()).flashing(
      "error" -> "Bad item add input" 
     ) 
    ) 
    }, 
    item => { 
     for { 
     ue <- usersService.findUserEntryByEmail(request.identity.email) 
     } yield ue match { 
     case Some(ue) => 
      val itemObj = Item(item.name, item.description, ue.companyId) 
      val xx = itemsService.addItemWithParts(itemObj, Seq(item.parts)) <-- want to catch exception thrown by this function 
      /* 
      * COMMENTED CODE PRINTS EXCEPTION ON CONSOLE, BUT DONT KNOW HOW TO REDIRECT/OK... 
      xx onComplete { 
      case Success(x) => { 
       println("Added ITEM: " + x) 
       Redirect(controllers.www.routes.Dashboard.dashboard) 
      } 
      case Failure(exp) => { 
       println("Exception while adding ITEM: " + exp) 
       Ok("Got exception: " + exp) 
      } 
      } 
      */ 
      Redirect(controllers.www.routes.Dashboard.dashboard) // +++ 
     case None => 
      Ok("Bad") 
     } 
    } 
) 
} 

私はonCompleteの成功から代わりのラインで)(私はリダイレクトを行うことができます思ったが、「+++」マークが、私は、このコンパイルエラーを取得:

type mismatch; 
[error] found : Unit 
[error] required: play.api.mvc.Result 
[error]   case Some(ue) => 
[error]      ^
[error] one error found 

私は遊びのドキュメントをチェックし、それが語りますErrorHandler(集中化された)にonServerErrorを追加するが、私はこのようにして何が欠けているのか知りたい。

私はまだScalaを学んでいますが、どんな助けもありがとうございます。

+0

良い場合は 'map'を、例外は' recover'を使います。 – rethab

答えて

1

onCompleteUnitを返します。 onCompleteを使用して副作用操作のみを行うことができます。

map,flatMapを使用して、新しい計算を構成して構築します。例外を処理して例外を返すには、recoverrecoverWithを使用します。ここ

は、あなたがこの

val result = 
for { 
ueOpt <- usersService.findUserEntryByEmail(request.identity.email) 
result <- ueOpt match { 
      case Some(ue) => 

       val itemObj = Item(item.name, item.description, ue.companyId) 
       val foo = itemsService.addItemWithParts(itemObj, Seq(item.parts)) 

       foo.map { value => 
       Redirect(controllers.www.routes.Dashboard.dashboard) 
       }.recover { case th => 
       InternalServerError("bad things happen in life.") 
       } 

      case None => Future.successful(BadRequest("no item found")) 
      } 
} yield result 

Futureを行うことができますどのようにある現在の将来の結果に新しい計算を構築するためにmapflatMapようなメソッドを提供します。また将来は、現在の将来の例外をスローするときに計算を構築するために、将来はrecoverrecoverWithを提供します。

def bar: Future[Int] = ??? 

bar.map { intValue => 
    //doSomething 
}.recover { 
    case ex: SQLException => //return some value 
    case _ => //ignore other exceptions and return default value 
} 
+0

Worked - ありがとう! – srvy

関連する問題