title: Best way to handle errors in Grails domain class validation
body: <p>We have an API command like "student/create" to create a new student object. The code looks like this:</p>
  
  <pre><code>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 -&gt;
          // set response.error to an appropriate value
          println error
      }
  } else {
      student.save()
  }
  </code></pre>
  
  <p>Our goal is to give a reasonable error message like "EMAIL_DUPLICATE" or "FIRSTNAME_LENGTH" on a validation fail, so we want to test the errors we get against a set of expected errors so we can respond like that.</p>
  
  <p>Here's what we get from that <code>println</code>:</p>
  
  <pre>Field error in object 'com.example.Student' on field 'email': rejected value [student@example.com]; codes [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]; arguments [email,class com.example.Student,student@example.com.org]; default message [Property [{0}] of class [{1}] with value [{2}] must be unique]</pre>
  
  <p>How can I figure out that this means the email is already used in the database so that I can tell the API user that?</p>
  
  <p>(to be clear, I want to give a computer-readable message like "EMAIL_DUPLICATE" instead of something like "Property email of class Student with value student@example.com must be unique")</p>