2

我在使用 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's 声明中(因为我认为我无法从表单和模型访问会话)。这就是它变得丑陋的时候。如果帖子无效,则 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电话打不通。我究竟做错了什么?处理插入/更新错误的最佳方法是什么?我对登录表单也有同样的问题,但它并没有那么糟糕,因为我实际上可以在登录表单声明时处理错误。

之前谢谢。

4

1 回答 1

1

假设错误是在数据库中不存在的完整性约束(如 0)上,那么这样的东西呢?

    postForm.bindFromRequest.fold(   
        formWithErrors => BadRequest(views.html.post.newPost(formWithErrors)),
        newPost => {
            request.session.get("id").map({ userId=> 
               models.Post.create(newPost._1, newPost._2, userId.toLong)       
               Redirect(routes.Application.index) 
            }).getOrElse{
                BadRequest(views.html.post.newPost(postForm.fill(newPost))) 
            }
        }   
    )

您不会向异常提供无效信息,也不会收到错误...

ps:我现在手头没有 scala 编译器来检查语法,我可能错过了括号或将括号与卷曲混合在一起:)

于 2012-07-11T13:00:23.537 回答