Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何自定义grails restful控制器错误响应_Rest_Grails_Grails Controller - Fatal编程技术网

如何自定义grails 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

我们如何定制grailsRestfulController错误响应?例如,我的一个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"
    },
    .....
}

使用所述的
国际化
功能。将以下内容添加到您的资源包
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"
    ]
}