I had an issue where I was sending a POST to Grails 1.3.7 with the format=json parameter on the query string.
Based on Grails withFormat documentation – http://grails.org/doc/1.3.7/ref/Controllers/withFormat.html, this parameter should cause the withFormat closure to execute the json closure within.
i.e.:
withFormat {
json {
// this logic should be executed if the query string has format=json
}
}
In this case, the controller method was serving multiple content types. There was some logic that should only run for forms, so a withFormat closure was added like so:
withFormat {
form {
// form specific logic
}
}
Note there was no json block, because there was no corresponding logic to execute if this was a json request. The problem was that the form block was being executed even on requests where we sent format=json on the query string.
Why would this happen?
Apparently if you don’t specify a matching closure within withFormat, Grails will still run one anyway. Grails documentation does note that if the request format is “all”, it will execute the first closure within the withFormat block. I suppose if you have a request format that doesn’t match one of the closures in a withFormat block, Grails defaults to run the first closure.
To fix this we put an empty json closure within withFormat, and Grails processed everything as expected from then on.