【发布时间】:2021-05-09 04:05:37
【问题描述】:
我正在开发一个可通过 rest api 访问的 java 后端。例如,有创建和更新产品的资源。根据用户的不同,产品可以具有不同的属性,我使用哈希图以动态方式处理这些属性(因此哪些产品具有哪些属性在其他地方定义)。属性可以是名称、来源、供应商、金额等。
示例:
public class Product
int id;
Set<ProductProperty>;
产品应通过 REST API 更新,并在正文中发送 JSON:
{productId: 1
supplier: XY
amount: 23
productCode: ZZ}
我遇到的问题是可以删除产品的特定属性。当然,所有其他属性都应相应更新。对于失败的属性,我想将错误返回给请求者。所以我的想法是返回一个 200 响应,它在响应正文中有一个 JSON 对象,例如:
{[errors:
{
"productCode": "ZZ",
"errorText": "Code lenght is less than 12 digits",
},
{
"foobarProperty": "123124124",
"errorText": "Property doest not exist for this product",
}
]}
这样我就可以在 UI 中显示错误(稍后将通过 react 进行设置),以便用户知道哪些属性无法更新以及原因。所以我想知道这是否是一个好方法,或者是否有我还不知道的最佳实践。
如果我想得更多,可以说产品也应该被退回,是否可以将产品设置为 json,包括错误部分:
{
productId: 1
supplier: XY
amount: 23
productCode: YY}, // has the updated prop
},
{
[errors:
{
"productCode": "ZZ",
"errorText": "Code lenght is less than 12 digits",
},
{
"foobarProperty": "123124124",
"errorText": "Property doest not exist for this product",
}
]}
【问题讨论】:
-
如果确实是错误情况,那么您可能需要考虑返回有效负载但带有 400 Bad Request code。
标签: java rest http error-handling