DrillLab
第 98 / 105 道98 / 105 · #362

常见的 HTTP 状态码

Give some HTTP response status codes

先自己答,再往下看Answer it yourself first

先说五个类别,再举例 —— 这样显得有体系:1xx 信息、2xx 成功3xx 重定向4xx 客户端错5xx 服务端错

含义什么时候用
200 OK成功GET / PUT / PATCH 成功
201 Created已创建POST 成功,建议带 Location 头
204 No Content成功但没内容DELETE 成功
301 / 302永久 / 临时重定向301 会被浏览器缓存,改错了很难收回
304 Not Modified没变,用缓存配 ETag / Last-Modified
400 Bad Request请求有问题参数缺失、格式错、校验失败
401 Unauthorized没登录 / token 无效「你是谁?」
403 Forbidden登录了但没权限「知道你是谁,但你不能干这个」
404 Not Found资源不存在
409 Conflict冲突重复注册、并发修改
422语义错误格式对但业务上不合法
429请求太多限流
500服务端异常未捕获的错误
502 / 503 / 504网关错 / 不可用 / 超时上游挂了、在维护、上游太慢

401 vs 403 是最常问的一对401 是「没认证」,403 是「认证了但没授权」
实践里有个细节:为了不泄露资源是否存在, 有些接口会把「没权限」也返回 404。

会追问:「业务错误该用 4xx 还是 200 带错误码?」——REST 风格用 4xx(让 HTTP 语义承载错误), 但要注意有些老网关会吞掉 4xx 的响应体GraphQL 则一律返 200, 错误放在 errors 字段里 —— 因为一个请求可能部分成功, 没法用单个状态码表达。这个对比答出来很加分, Federation 那门课里 extensions.code就是干这个的。

Name the five classes first, then give examples — it reads as organised: 1xx informational, 2xx success, 3xx redirect, 4xx client error, 5xx server error.

CodeMeansWhen
200 OKSuccessA successful GET / PUT / PATCH
201 CreatedCreatedA successful POST — send a Location header
204 No ContentSuccess, nothing to returnA successful DELETE
301 / 302Permanent / temporary redirectBrowsers cache 301, so a wrong one is hard to take back
304 Not ModifiedUnchanged, use your cachePaired with ETag or Last-Modified
400 Bad RequestThe request is wrongMissing parameter, bad format, failed validation
401 UnauthorizedNot logged in, or the token is invalid“Who are you?”
403 ForbiddenLogged in but not allowed“I know who you are, and you cannot do this”
404 Not FoundNo such resource
409 ConflictConflictDuplicate signup, concurrent edit
422Semantically wrongWell-formed but invalid for the business rules
429Too many requestsRate limiting
500Server failedAn uncaught error
502 / 503 / 504Bad gateway / unavailable / timeoutUpstream is down, in maintenance, or too slow

401 vs 403 is the pair they ask about most: 401 means not authenticated, 403 means authenticated but not authorised.
One detail from practice: to avoid leaking whether a resource exists, some endpoints return 404 for “not allowed” as well.

Follow-up: “Should a business error be a 4xx or a 200 with an error code?” — REST says 4xx, so the HTTP semantics carry the error, but watch out: some older gateways swallow the body of a 4xx. GraphQL always returns 200 and puts errors in the errors field, because one request can be partially successful and no single status code says that. Drawing that contrast earns you points — in the Federation course, extensions.code is exactly this.