Returning Grails Validation Errors for Ajax Calls

January 6, 2011

I’m using Grails to create a REST service, and its built-in JSON formatting makes receiving and returning objects easy. When I get validation errors, I’d like to return the errors in JSON in a format that’s easy to use by my client. With a web client, Grails (and most other validation frameworks) by default outputs a list of human-friendly error messages. Ideally, what I’d like to return from my REST service is a list of strings, where each string is one field error.

Incidentally, REST’s HTTP status codes make it easy to distinguish when I’m returning objects vs. error messages. If I return a 200 or 201 status code, it’s success, and my client should expect an object from my data model back. If I return a 500 status code, my client should expect a list of error strings back.

It took me a little poking around in javadocs and Grails source to figure it out, but here’s the syntax that will work:

response.status = 500
render myGormObject.errors.allErrors.collect {
} as JSON

List of All Grails Validation Constraints

February 22, 2010

For some reason, Grails decided to delete their published list of all validation constraints. This official-sounding page just sends you to the reference docs, and its validation page gives the unhelpful message that

A complete reference for the available constraints can be found on the reference guide

I’m not sure what other reference guide this could be referring to, not to mention what it would mean for this information to be found “on” the reference guide, as opposed to “in” it.

Update: @mr_paul_woods sent me to the Grails docs and told me to look in the sidebar. Turns out that I wasn’t supposed to click Validation on the right pane, but rather find “Constraints” in the unrelated left pane. There’s no way to get this list on a page by itself, so here they are to be helpful: