我们如何自定义grails RestfulController 错误响应?例如,我的一个restful控制器在尝试保存对象时默认返回错误响应。
{
"errors":
[
{
"object": "com.test.Task",
"field": "description",
"rejected-value": null,
"message": "Property [description] of class [class com.test.Task] cannot be null"
}
]
}
我想自定义响应。
{
"errors" :
{
"message": "Property [description] of class [class com.test.Task] cannot be"
},
{
"message": "This is going to be any 2nd message"
},
.....
}
答案 0 :(得分:2)
我找到了解决方案
您只需在org.grails.datastore.mapping.validation.ValidationErrors
类
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]
}
回复将是:
{
"errors": [
"Property [description] of class [class com.test.Task] cannot be",
"This is going to be any 2nd message"
]
}
答案 1 :(得分:1)
使用here所述的Internationalization
功能。将以下内容添加到资源包messages.properties
。
task.description.nullable = your message
或
com.test.Task.description.nullable = your message