一个好的 error response 做两件事:它使用正确的 HTTP status code(机器可读的信号),并返回一个一致、有结构的 body,让开发者能据此行动。不一致的 error 形状是 client 侧最大的痛苦来源之一。
使用标准错误格式:RFC 7807(problem+json)
RFC 7807 定义了一个标准的“problem details” body,配有专用的 media type,因此你 API 中的每个错误看起来都一样:
http
HTTP/1.1 404 Not Found
Content-Type: application/problem+json
{
"type": "https://api.example.com/errors/not-found",
"title": "Resource not found",
"status": 404,
"detail": "No user exists with id 999",
"instance": "/users/999"
}
