Returning Grails Validation Errors for Ajax Calls

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 {
    message(error:it,encodeAs:'HTML')
} as JSON
Advertisements

3 Responses to Returning Grails Validation Errors for Ajax Calls

  1. mcv says:

    Thank. I’m looking exactly for something like this. One detail, though: 500 means a server error, not a validation error. I don’t think HTTP has an error code for validation errors, so I’m not sure if status codes should really be used like that.

    How are you going to distinguish a validation error from a real server error?

  2. mcv says:

    A worse problem is that it doesn’t actually work. I just get “Property [name] of class [class CommentCommand] cannot be null” instead of the meaningful custom error message that I got pre-Ajaxification.

  3. grails ajax says:

    How do you render the JSON response for the list of validation errors in your GSP?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: