mehmood
mehmood

Reputation: 301

how to customize grails restful controller error response

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

Answers (2)

mehmood
mehmood

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

saw303
saw303

Reputation: 9072

Use the Internationalization feature described here. Add the following to your resource bundle messages.properties.

task.description.nullable = your message

or

com.test.Task.description.nullable = your message

Upvotes: 1

Related Questions