自定义由 grails 域约束验证失败返回的默认错误对象的最佳方法是什么?
我得到的当前 JSON 是
{"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]"
}]}
我想从上面的响应中去掉“对象”并希望有“错误代码”。
我对 grails 很陌生,并且在几个基本实现方面苦苦挣扎。提前致谢。
最佳答案
您可以新建一个 custom marshaller for validation errors并在 Bootstrap.groovy
中注册作为
JSON.registerObjectMarshaller( new MyCustomValidationErrorsMarshaller() )
只需更换 this line通过您的
error-code
例如:json.property( "error-code", HttpStatus.UNPROCESSABLE_ENTITY.value() )
一种快速的方法是在 bootstrap 中注册对象编码器,但这会使 bootstrap 类膨胀。编写自定义编码器更简洁。
另一种方法是写一个 interceptor和 intercept response然后只需替换
object
来自带有您想要的错误代码的错误响应。
关于validation - Grails 3 自定义错误对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34474889/