validationgrailsgrails-ormcustomizing

Grails 3 Customizing Error object


What is the best way to customize the default error object returned by grails domain constraint validation failures?

The current JSON I am getting is

{"errors": [{"object": "com.self.learning.grails.demo.api.Person", 
    "field": "name",
    "rejected-value": "K12332434",
    "message": "Property [orgKey] of class [class com.self.learning.grails.demo.api.Person] with value [K123324343432432432432] exceeds the maximum size of [12]"
}]}

I want to get rid of "object" from the above response and want to have "error-code".

I am pretty new to grails and struggling with few basic implementations. Thanks in advance.


Solution

  • You can create a new custom marshaller for validation errors and register it in Bootstrap.groovy as

    JSON.registerObjectMarshaller( new MyCustomValidationErrorsMarshaller() )
    

    Just replace this line by your error-code for example:

    json.property( "error-code", HttpStatus.UNPROCESSABLE_ENTITY.value() )
    

    A quick way would be to register object marshaller right in the bootstrap but that will bloat bootstrap class. It is cleaner to write a custom marshaller.

    Another way would be write an interceptor and intercept response then just replace object from error response with your desired error code.