有没有方法可以忽略以下没有failed
的地图/平面图?
这就是我所拥有的:
def delete(serverId: UUID) = authAction.async { implicit request =>
val user = request.user.get
serverService.findByIdAndUserId(serverId, user.id.get)
.flatMap{s =>
if (s.isEmpty) {
Future.failed(new DeleteFailedException)
// Can I return a `NotFound("...")` here instead of failed?
} else {
Future.successful(s.get)
}
}
.map{s =>
serverService.delete(s)
}.map{_ =>
Ok(Json.toJson(Map("success" -> "true")))
}
}
当我在NotFound("...")
中返回flatMap
时,以下map
仍然会被执行。有没有办法忽略以下地图/平面图?
答案 0 :(得分:1)
而不是使用异常执行Future.failed。你可以返回一个。关于它们的好处是你可以在它上进行模式匹配,然后构造适当的http响应。
def delete(serverId: UUID) = authAction.async { implicit request =>
val user = request.user.get
serverService.findByIdAndUserId(serverId, user.id.get)
.flatMap{s =>
if (s.isEmpty) {
Left(new DeleteFailedException)
} else {
Right(s.get)
}
}
.map{s => s match {
case Left(notFound) =>
// construct the Json for failure
case Right(s) =>
serverService.delete(s)
// construct json for success.
}}
}
答案 1 :(得分:1)
认为应该没问题(我假设findByIdAndUserId
返回Future [Option [_]],而不是Option[_]
,如您在评论中所回答的那样)。在我的方法中,我还删除了get
和不必要的map
def delete(serverId: UUID) = authAction.async { implicit request =>
val user = request.user.get
request.user.flatMap(_.id).fold {
Future.successfull(NotFound("no user"))
} {userId =>
serverService.findByIdAndUserId(serverId, userId).map {
case None =>
NotFound("no server")
case Some(s) =>
serverService.delete(s)
Ok(Json.toJson(Map("success" -> "true")))
}
}
}