gpt4 book ai didi

rest - 如何自定义grails Restful Controller 错误响应

转载 作者:行者123 更新时间:2023-12-02 14:23:58 26 4
gpt4 key购买 nike

我们如何自定义grails RestfulController 错误响应?例如,我的 Restful Controller 之一在尝试保存对象时默认返回错误时的以下响应。

{
"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"
},
.....
}

最佳答案

我找到了解决方案

您需要做的是在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"
]
}

关于rest - 如何自定义grails Restful Controller 错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24336542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com