非 运行 进程的最佳 HTTP 错误代码?

An optimum HTTP error code for process not running?

我正在构建一个休息服务器,客户端将调用它来中止一个较长的 运行 进程。

/abort/{processID}

现在如果没有找到带有 processID 的进程,我将返回 404 Not Found

但是如果进程已经completed/is而不是运行,那么应该正确的HTTP Error code是一样的吗?

406 Not Acceptable 与 Accept header 相关(因此我认为我不会使用)。

400 Bad Request 似乎太笼统了。

寻求关于哪个 header 最适合它的建议?

简答

以下是一些可能适合您的合理选择:

  • 404 未找到
  • 410 消失了
  • 409 冲突
  • 403禁止

正确的选择依赖于语义 process has already been completed/is not 运行:

  • 如果进程不再存在,请考虑 404410,具体取决于条件是否永久。
  • 如果可以找到具有给定 ID 的进程,但由于与进程的当前状态冲突而无法完成中止该进程的尝试,您可以选择 409.
  • 如果其他原因禁止操作,选择403

该进程不再存在

如果进程不再存在,您可以在404410之间进行选择,具体取决于条件是否(或可以确定条件是否)永久存在。

请参阅 RFC 7231 中的以下引述:

6.5.4. 404 Not Found

The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists. A 404 status code does not indicate whether this lack of representation is temporary or permanent; the 410 (Gone) status code is preferred over 404 if the origin server knows, presumably through some configurable means, that the condition is likely to be permanent. [...]

6.5.9. 410 Gone

The 410 (Gone) status code indicates that access to the target resource is no longer available at the origin server and that this condition is likely to be permanent. If the origin server does not know, or has no facility to determine, whether or not the condition is permanent, the status code 404 (Not Found) ought to be used instead. [...]

进程存在,但操作产生冲突

如果进程存在,404410 不是好的选择。

如果由于与进程的当前状态冲突而无法完成中止现有进程的尝试,您应该考虑 409 以及描述冲突原因的负载。

查看引用:

6.5.8. 409 Conflict

The 409 (Conflict) status code indicates that the request could not be completed due to a conflict with the current state of the target resource. This code is used in situations where the user might be able to resolve the conflict and resubmit the request. The server SHOULD generate a payload that includes enough information for a user to recognize the source of the conflict. [...]

进程存在,但由于某种原因禁止操作

最后一个选项是 403。此状态代码经常用于 授权 问题,当凭据有效但不足以授权请求时。

然而 403 比这要广泛得多,可用于指示请求因 与凭据无关的原因 而被禁止。请确保您提供的负载描述了为什么禁止该操作。

查看引用:

6.5.3. 403 Forbidden

The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).

If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT automatically repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.

An origin server that wishes to "hide" the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found).