【问题标题】:Handling Error on Insert PlayFramework 2.0 Scala处理插入 PlayFramework 2.0 Scala 上的错误
【发布时间】: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


    【解决方案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 编译器来检查语法,我可能错过了括号或将括号与花括号混合在一起:)

    【讨论】:

    • 这将解决 postForm 的问题,但我认为它不会解决另一个问题:数据库上的双重数据。例如:用户注册时的电子邮件。无论如何感谢您的回答。
    • 您可以在模型中捕获数据库错误并让您的 User.create 方法返回选项或错误并从那里开始
    • 你检查过这个吗? stackoverflow.com/questions/6323961/…
    猜你喜欢
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多