0

在以下代码中,该函数应返回实例,Future[Result]但我无法这样做。代码查询数据库,数据库返回Future[User]。我认为我能够正确映射未来的成功部分,但不能正确映射失败部分。请参阅函数末尾的注释。

def addUser = silhouette.UserAwareAction.async{ implicit request => {
    val body: AnyContent = request.body
    val jsonBody: Option[JsValue] = body.asJson

//check for message body. It should be json
    jsonBody match {
      case Some(json) => { //got json in message body.
        val readableString: String = Json.prettyPrint(json)
        println(s"received Json ${readableString}")
        val userProfile: Option[UserProfile] = json.asOpt[UserProfile] //check if json conforms with UserProfile structure
        userProfile match {
          case Some(profile) => { //json conforms to UserProfile.
            println(s"received profile ${profile}")

            val loginInfo = LoginInfo(CredentialsProvider.ID, profile.externalProfileDetails.email)
            println(s"checking if the user with the following details exists ${loginInfo}")

            val userFuture: Future[Option[User]] = userRepo.find(loginInfo) // userFuture will eventually contain the result of database query i.e Some(user) or None
            userFuture.map { user:Option[User] => { //Future successful
                case Some(user) => { //duplicate user
                  println("duplicate user" + user)
                  Future  { Ok(Json.toJson(JsonResultError("duplicate user")))   }
                }
                case None => { //unique user
                    Future { Ok(Json.toJson(JsonResultSuccess("Not duplicate user"))) }
                }
              }
            }

/***This is the part I am unable to code. I suppose the addUser method expect that the last statement (its return value) is Future{....} but it seems that they way I have coded it, it is not the case. If I remove this code and just type Future { Ok(Json.toJson(JsonResultSuccess("Internal Server Error"))) } then code compiles. But that logic is not correct because then this message will be sent all the time, not when the future fails!***/
            val userFailedFuture:Future[Throwable] = userFuture.failed
            userFailedFuture.map {x=> Future { Ok(Json.toJson(JsonResultSuccess("Internal Server Error"))) }}

          }

            //Json doesn't conform to UserProfile
          case None => Future {  Ok(Json.toJson(JsonResultError("Invalid profile")))  } /*TODOM - Standardise error messages. Use as constants*/
        }
      }
        //message body is not json. Error.
      case None => Future {  Ok(Json.toJson(JsonResultError("Invalid Body Type. Need Json"))) }/*TODOM - Standardise error messages. Use as constants*/

      }
    }
  }
4

2 回答 2

3

您不必在将来包装您的结果,因为您已经从未来值进行评估,这很简单:

   futureValue.map{value => //RESULT
}

并在 Future 处理错误时,建议使用带有 map 的恢复,例如:

    futureValue.map{value => //RESULT
}.recover{case ex: Exception => //RESULT
}

如果结果已经在地图或恢复块中,则无需将结果包装在 Future 中。由于地图外的最终结果和 Future 的恢复将是 Future[Result]。因此,如果你包装另一个 Future,它将变成 Future[Future[Result]]。

于 2018-04-18T05:49:10.630 回答
0

同意@geek94 的回答。一、修改:

目前尚不清楚您使用的是什么库,但在大多数情况下不需要future.recover显式调用。每个像样的 http 库(例如 akka-http)都将失败的未来视为 InternalServerError。

于 2018-04-18T08:52:13.210 回答