Thursday, June 17, 2010

Slick Grails Error Reporting

Here's a slick way of nicely reporting errors using Grails' built-in validation machinery:
package adminprototype
class AdminController {
def index = { }
def createDatabaseConnection = {
render Utils.saveAndReport(
new DatabaseConnection(params))
}
}
package adminprototype
class Utils {
static String saveAndReport(Object o){
return o.save()?"success":reportErrors(o)
}
static String reportErrors(Object o){
def error = o.errors.getFieldError()
String field = error.getField().toString()
field = field.replaceAll("\\B([A-Z])", " \$1")
field = field.toLowerCase()
String bogus = error.getRejectedValue()
return "The "+field+" cannot be "+(bogus?bogus:"blank")+"."
}
}
Now if I leave out the field "databaseName" in a request like this:
http://localhost:8080/AdminPrototype/admin/createDatabaseConnection?port=1234
I get a really nice error message with the camel case field name converted into a space delimited name:
The database name cannot be blank.