Reputation: 301
How do we customize grails RestfulController error response? For example one of my restful controller returning following response by default on error while trying to save object.
{
"errors":
[
{
"object": "com.test.Task",
"field": "description",
"rejected-value": null,
"message": "Property [description] of class [class com.test.Task] cannot be null"
}
]
}
I would like to customize the response as bellow.
{
"errors" :
{
"message": "Property [description] of class [class com.test.Task] cannot be"
},
{
"message": "This is going to be any 2nd message"
},
.....
}
Upvotes: 1
Views: 1306
Reputation: 301
I found the solution
All you need is Register Custom Objects Marshallers on org.grails.datastore.mapping.validation.ValidationErrors
class
def messageSource //inject messageSource
JSON.registerObjectMarshaller(ValidationErrors) { validationErrors ->
def errors = [] //add all errors into this list
validationErrors.target.errors.allErrors.each { error ->
errors.add(messageSource.getMessage(error, null)) //get messages from properties file.
}
//return map with errors list
return ["errors":errors]
}
Response will be:
{
"errors": [
"Property [description] of class [class com.test.Task] cannot be",
"This is going to be any 2nd message"
]
}
Upvotes: 2