如何自定义grails restful控制器错误响应
我们如何定制grailsRestfulController错误响应?例如,我的一个restful控制器在尝试保存对象时,在出现错误时默认返回以下响应如何自定义grails restful控制器错误响应,rest,grails,grails-controller,Rest,Grails,Grails Controller,我们如何定制grailsRestfulController错误响应?例如,我的一个restful控制器在尝试保存对象时,在出现错误时默认返回以下响应 { "errors": [ { "object": "com.test.Task", "field": "description", "rejected-value": null, "message": "Property [description] of class [cl
{
"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"
},
.....
}
使用所述的
国际化
功能。将以下内容添加到您的资源包messages.properties
task.description.nullable = your message
或
我找到了解决办法
您只需在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"
]
}
{
"errors": [
"Property [description] of class [class com.test.Task] cannot be",
"This is going to be any 2nd message"
]
}