验证 – Grails 3自定义错误对象

自定义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,例如:

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

一种快速的方法是在引导程序中注册对象编组器,但这将使膨胀引导类膨胀.编写自定义编组器更清晰.

另一种方法是写一个interceptorintercept response,然后用你想要的错误代码替换错误响应中的对象.

点赞