如何自定义grails restful controller错误响应

时间:2014-06-20 22:26:49

标签: rest grails grails-controller

我们如何自定义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"
    },
    .....
}

2 个答案:

答案 0 :(得分:2)

我找到了解决方案

您只需在org.grails.datastore.mapping.validation.ValidationErrors

上注册自定义对象Marshallers即可
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