Grails 注册了一个ValidationErrorsMarshaller
处理所有错误的实例,因此您的 FieldError 编组器将永远不会被调用。
//convertAnother is not called for each error. That's the reason of your custom marshalled not been called.
for (Object o : errors.getAllErrors()) {
if (o instanceof FieldError) {
FieldError fe = (FieldError) o;
writer.object();
json.property("object", fe.getObjectName());
json.property("field", fe.getField());
json.property("rejected-value", fe.getRejectedValue());
Locale locale = LocaleContextHolder.getLocale();
if (applicationContext != null) {
json.property("message", applicationContext.getMessage(fe, locale));
}
else {
...
查看ConvertersGrailsPlugin
(插件的描述符)这是注册为 Spring Bean,因此您可以创建另一个 bean 并使用相同的名称注册,覆盖marshalObject()
以满足您的需求(未测试,可能需要更多代码)。
class MyErrorsMarshaller implements ObjectMarshaller<JSON>, ApplicationContextAware {
ApplicationContext applicationContext;
public boolean supports(Object object) {
return object instanceof Errors;
}
public void marshalObject(Object object, JSON json) throws ConverterException {
...
}
}
资源.groovy
jsonErrorsMarshaller(MyErrorsMarshaller)
errorsJsonMarshallerRegisterer(ObjectMarshallerRegisterer) {
marshaller = { MyErrorsMarshaller om -> }
converterClass = grails.converters.JSON
}
ValidationErrorsMarshaller的参考。
ConvertersGrailsPlugin的参考。