更正无效 POST 请求的响应代码
Correct response code for an invalid POST request
我刚刚注意到我的申请中可能有不正确的地方。在很多时候,我有 post 表单需要某些输入参数才能继续插入数据。例如,为了向您的联系人列表添加一个用户,首先该用户必须存在,我这样做很简单
$db = \Database::connection();
$user = new \Models\User();
$user->getById($data['id'], $db);
if ($user->id) {
if (\Models\User::auth()->addContact($user, $db)) {
return \Response::json(['text' => 'Contact added']);
} else {
throw new \Exception('User not found', 404);
}
}
忽略所有其他可能的错误,只关注 user not found
一个错误,我只是注意到我正在 returning 一个 404 代码,我对此表示怀疑。在我编写这段代码时,我肯定是被消息中的 not found
部分激怒了,并自动假定这是一个 404 错误。但是现在想想404错误其实是"Resource not found",我的逻辑是,我不求资源怎么会找不到资源呢
return POST 请求的 404 错误是否正确,或者我应该切换到 400?
正在更新的资源是用户联系人列表 - 类似于 User/[userid]/ContactList ?此资源已被正确识别,但添加到联系人列表的用户无效。
在http rfc 404是"The server has not found anything matching the Request-URI..."
我会发现在找到要更新的资源的基础上出现此错误是令人惊讶的行为。如果您要 return 一个 404,那么它应该包含一个消息正文,准确指示找不到哪个资源。
400 表示 "the request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications"。我认为语法是正确的,因此 500(内部服务器错误)加上响应正文中的解释更为合适。
我刚刚注意到我的申请中可能有不正确的地方。在很多时候,我有 post 表单需要某些输入参数才能继续插入数据。例如,为了向您的联系人列表添加一个用户,首先该用户必须存在,我这样做很简单
$db = \Database::connection();
$user = new \Models\User();
$user->getById($data['id'], $db);
if ($user->id) {
if (\Models\User::auth()->addContact($user, $db)) {
return \Response::json(['text' => 'Contact added']);
} else {
throw new \Exception('User not found', 404);
}
}
忽略所有其他可能的错误,只关注 user not found
一个错误,我只是注意到我正在 returning 一个 404 代码,我对此表示怀疑。在我编写这段代码时,我肯定是被消息中的 not found
部分激怒了,并自动假定这是一个 404 错误。但是现在想想404错误其实是"Resource not found",我的逻辑是,我不求资源怎么会找不到资源呢
return POST 请求的 404 错误是否正确,或者我应该切换到 400?
正在更新的资源是用户联系人列表 - 类似于 User/[userid]/ContactList ?此资源已被正确识别,但添加到联系人列表的用户无效。
在http rfc 404是"The server has not found anything matching the Request-URI..." 我会发现在找到要更新的资源的基础上出现此错误是令人惊讶的行为。如果您要 return 一个 404,那么它应该包含一个消息正文,准确指示找不到哪个资源。
400 表示 "the request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications"。我认为语法是正确的,因此 500(内部服务器错误)加上响应正文中的解释更为合适。