【发布时间】:2025-12-12 05:35:02
【问题描述】:
我们有一个像“student/create”这样的 API 命令来创建一个新的学生对象。代码如下所示:
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”中的字段错误:拒绝值 [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];论据 [电子邮件,com.example.Student 班级,student@example.com.org];默认消息 [类 [{1}] 的属性 [{0}],值为 [{2}] 必须是唯一的]
我怎样才能知道这意味着该电子邮件已在数据库中使用,以便我可以告诉 API 用户?
(需要明确的是,我想提供一条计算机可读的消息,例如“EMAIL_DUPLICATE”,而不是“带有值 student@example.com 的 Student 班级的财产电子邮件必须是唯一的”)
【问题讨论】:
标签: grails groovy error-handling