【发布时间】:2013-08-30 11:28:21
【问题描述】:
我正在编写一个 REST API,但我偶然发现了一个问题。返回验证错误的最佳方法是什么。
到目前为止,我一直在返回转储到一般错误代码中的错误消息(例如错误请求)
{
"status": 400,
"error": {
"code": 1, // General bad request code
"message": [
"The Key \"a\" is missing",
"The Key \"b\" is missing",
"The Key \"c\" is missing",
"Incorrect Format for field \"y\""
]
}
)
我对良好的 API 响应应该是什么样子进行了更多研究,并想到了以下选项:
-
在第一个遇到的错误处停止并返回带有特定错误代码的响应
{ "status": 400, //Same as the HTTP header returned "error" { "code": 1, // Specific field validation error code "message": "Field \"x\" is missing from the array structure", "developer_message": "The request structure must contain the following fields {a,b,c{x,y,z}}", "more_info" => "www.api.com/help/errors/1" } ) -
解析所有请求数据并返回多个字段验证错误。
{ "status": 400, "error": { "code": 1 //General bad Request code "message": "Bad Request", "developer_message": "Field validation errors." "more_info": "www.api.com/help/errors/1", "error_details": { 0: { "code": 2 // Specific field validation error code "message": "Field \"x\" is missing from the array structure", "developer_message": "The request structure must contain the following fields {a,b,c{x,y,z}}", "more_info": "www.api.com/help/errors/2" }, 1: { "code": 3 // Specific field validation error code "message": "Incorrect Format for field \"y\"", "developer_message": "The field \"y\" must be in the form of \"Y-m-d\"", "more_info": "www.api.com/help/errors/3" } } } }
在我看来,选项 2 是正确的方法(它为开发人员/最终用户提供了更多有用的信息,并且服务器负载可能更低(更少的请求/无需重新验证有效数据/无需计算签名和对用户进行身份验证)),但我正在徘徊什么是最佳实践,以及是否有另一种方法来处理此类问题。
如果我在脚本流程中遇到一个致命错误,我认为选项 1 仍然有效。(不是验证错误)
请注意,代码只是一个简单的数组,以便更容易理解。响应格式为 JSON 或 XML。
【问题讨论】:
-
我想知道是否有人去了#2,也许有任何改进,所以我开了一个赏金。
-
这个 API 有什么用途,错误消息的目的是什么?这些消息是否会显示给最终用户?每秒/分钟/天预计有多少请求?没有这些信息,您的问题的答案就不可能准确。您没有答案,因为这个问题太宽泛了,这实际上取决于 API 的使用情况。