【发布时间】:2012-07-11 01:56:09
【问题描述】:
我在使用 Play Framework 2.0 中的异常向数据库插入(或更新)新数据时遇到问题。我的模型是一篇博文,定义如下代码:
case class Post(title: String,
content: String,
created: String,
lastUpdate: String,
writer: Long,
id: Long = 0)
然后我在插入函数上这样做:
def create(title: String, content: String, userId: Long) = {
DB.withConnection { implicit connection =>
SQL("INSERT INTO post (title, content, created, writer) VALUES ({title}, {content}, NOW(), {writer})")
.on(
'title -> title,
'content -> content,
'writer -> userId).executeUpdate()
}
还有形式:
val postForm = Form(
tuple(
"title" -> nonEmptyText,
"content" -> nonEmptyText))
我在表单中没有 userId 字段,因为我不相信用户在他们自己的 ID 上的输入。我从会话中得到它。无论如何,这就是为什么我不能直接将验证代码放在postForm 的声明中(因为我认为我无法从表单和模型访问会话)。这就是它变得丑陋的时候。如果帖子无效,则 anorm 会引发异常,因此我需要在 fold 函数之后将错误传递给用户,例如:
postForm.bindFromRequest.fold(
formWithErrors => BadRequest(views.html.post.newPost(formWithErrors)),
newPost => {
try {
val userId = request.session.get("id").getOrElse("0")
models.Post.create(newPost._1, newPost._2, userId.toLong)
} catch {
case e => BadRequest(views.html.post.newPost(postForm.fill(newPost)))
}
Redirect(routes.Application.index)
})
首先,try-catch 很难看。其次,BadRequest 调用不起作用。我究竟做错了什么?处理插入/更新错误的最佳方法是什么?我的登录表单也有同样的问题,但它并没有那么糟糕,因为我实际上可以在登录表单声明时处理错误。
之前谢谢。
【问题讨论】:
标签: scala playframework-2.0 anorm