Grails领域类验证中处理错误的最佳方法

3
我们有一个API命令叫做“student/create”,用于创建新的学生对象。 代码如下:
def student = new Student(firstName: firstName, lastName: lastName, email: email)

if (! student.validate()) {
    response.error = "UNKNOWN_ERROR" // in case we can't find anything better

    student.errors.allErrors.each { error ->
        // set response.error to an appropriate value
        println error
    }
} else {
    student.save()
}

我们的目标是在验证失败时提供一个合理的错误消息,如“EMAIL_DUPLICATE”或“FIRSTNAME_LENGTH”,因此我们想将获得的错误与一组预期的错误进行测试,以便我们可以像这样做出响应。
以下是我们从println中获取的内容:
对象' com.example.Student '上字段' email '的字段错误:拒绝的值[student@example.com];代码[com.example.Student.email.unique.error.com.example.Student.email、com.example.Student.email.unique.error.email、com.example.Student.email.unique.error.java.lang.String、com.example.Student.email.unique.error、student.email.unique.error.com.example.Student.email、student.email.unique.error.email、student.email.unique.error.java.lang.String、student.email.unique.error、com.example.Student.email.unique.com.example.Student.email、com.example.Student.email.unique.email、com.example.Student.email.unique.java.lang.String、com.example.Student.email.unique、student.email.unique.com.example.Student.email、student.email.unique.email、student.email.unique.java.lang.String、student.email.unique、unique.com.example.Student.email、unique.email、unique.java.lang.String、unique];参数[email、class com.example.Student、student@example.com.org];默认消息[类[{1}]的属性[{0}]的值[{2}]必须是唯一的。]
我该怎么确定这意味着电子邮件已经在数据库中使用了,以便我可以告诉API用户呢?
(明确一下,我想提供一个计算机可读的消息,如“EMAIL_DUPLICATE”,而不是像“Property email of class Student with value student@example.com must be unique”这样的东西)
1个回答

5

不确定它是否适用于除此之外的更多情况,但是这样做可以:

    println "${error.objectName}_${error.codes[-1]}".toUpperCase()

你需要到达任何地方吗?

我将 error.objectName 更改为 error.field,就目前而言效果非常好。我们得到了 EMAIL_UNIQUEFIRSTNAME_SIZE.TOOSMALLLASTNAME_BLANK 等等。这正是我们想要的信息!谢谢! - Tom Marthenal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接