10.12.3 Vnd.Error Support

Vnd.Error is a standardised way of expressing an error response.

By default when a validation error occurs when attempting to POST new resources then the errors object will be sent back allow with a 422 respond code:

  1. $ curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST -d "" http://localhost:8080/books
  2. HTTP/1.1 422 Unprocessable Entity
  3. Server: Apache-Coyote/1.1
  4. Content-Type: application/json;charset=ISO-8859-1
  5. {
  6. "errors": [
  7. {
  8. "object": "rest.test.Book",
  9. "field": "title",
  10. "rejected-value": null,
  11. "message": "Property [title] of class [class rest.test.Book] cannot be null"
  12. }
  13. ]
  14. }

If you wish to change the format to Vnd.Error then simply register grails.rest.render.errors.VndErrorJsonRenderer bean in grails-app/conf/spring/resources.groovy:

  1. beans = {
  2. vndJsonErrorRenderer(grails.rest.render.errors.VndErrorJsonRenderer)
  3. // for Vnd.Error XML format
  4. vndXmlErrorRenderer(grails.rest.render.errors.VndErrorXmlRenderer)
  5. }

Then if you alter the client request to accept Vnd.Error you get an appropriate response:

  1. $ curl -i -H "Accept: application/vnd.error+json,application/json" -H "Content-Type: application/json" -X POST -d "" http://localhost:8080/books
  2. HTTP/1.1 200 OK
  3. Server: Apache-Coyote/1.1
  4. Content-Type: application/vnd.error+json;charset=ISO-8859-1
  5. [
  6. {
  7. "logref": "book.nullable,
  8. "message": "Property [title] of class [class rest.test.Book] cannot be null",
  9. "_links": {
  10. "resource": {
  11. "href": "http://localhost:8080/rest-test/books"
  12. }
  13. }
  14. }
  15. ]