我们有一个API命令叫做“student/create”,用于创建新的学生对象。 代码如下:
我们的目标是在验证失败时提供一个合理的错误消息,如“EMAIL_DUPLICATE”或“FIRSTNAME_LENGTH”,因此我们想将获得的错误与一组预期的错误进行测试,以便我们可以像这样做出响应。
以下是我们从
(明确一下,我想提供一个计算机可读的消息,如“EMAIL_DUPLICATE”,而不是像“Property email of class Student with value student@example.com must be unique”这样的东西)
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”这样的东西)
error.objectName
更改为error.field
,就目前而言效果非常好。我们得到了EMAIL_UNIQUE
、FIRSTNAME_SIZE.TOOSMALL
、LASTNAME_BLANK
等等。这正是我们想要的信息!谢谢! - Tom Marthenal