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

Tom*_*nal 3 error-handling grails groovy

我们有一个像“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()
}
Run Code Online (Sandbox Code Playgroud)

我们的目标是在验证失败时提供合理的错误消息,例如“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];默认消息 [具有值 [{2}] 的类 [{1}] 的属性 [{0}] 必须是唯一的]

我怎样才能知道这意味着电子邮件已在数据库中使用,以便我可以告诉 API 用户这一点?

(需要明确的是,我想提供一条计算机可读的消息,例如“EMAIL_DUPLICATE”,而不是“具有值student@example.com的Student类的属性电子邮件必须是唯一的”)

tim*_*tes 5

不确定它是否可以在更多情况下工作,而不仅仅是这种情况,但可以:

    println "${error.objectName}_${error.codes[-1]}".toUpperCase()
Run Code Online (Sandbox Code Playgroud)

能带你到附近吗?