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