【发布时间】:2012-09-25 15:17:30
【问题描述】:
下面是一个很常见的play framework 2控制器:
def save(ideaId : Long) = CORSAction { request =>
Idea.findById(ideaId).map { idea =>
request.body.asJson.map { json =>
json.asOpt[Comment].map { comment =>
comment.copy(idea = idea).save.fold(
errors => JsonBadRequest(errors),
comment => Ok(toJson(comment).toString)
)
}.getOrElse (JsonBadRequest("Invalid Comment entity"))
}.getOrElse (JsonBadRequest("Expecting JSON data"))
}.getOrElse (JsonBadRequest("Could not find idea with id '%s'".format(ideaId)))
}
我觉得所有那些嵌套的 .map 有点烦人,而且我也觉得每个错误处理都在底部有点乏味
您将如何改进它以使其更具可读性,同时保持功能性惯用的 scala 代码?
我在想可能是这样的(它是伪代码,仍然无法编译)
def save(ideaId : Long) = CORSAction { request =>
val idea = Idea.findById(ideaId).getOrElse(
return JsonBadRequest("Could not find idea with id '%s'".format(ideaId)))
val json = request.body.asJson.getOrElse(
return JsonBadRequest("Expecting JSON data"))
val comment = json.asOpt[Comment].getOrElse(
return JsonBadRequest("Invalid Comment entity"))
comment.copy(idea = idea).save.fold(
errors => JsonBadRequest(errors),
comment => Ok(toJson(comment).toString)
)
}
ps:我知道最好避免使用return语句...
【问题讨论】:
-
恭喜,你刚刚发明了单子!
-
删除
returns 作为启动器。哦,等等,他们应该打破save方法的流程吗?
标签: scala error-handling idioms