API契约:迁移聊天商品与自动化错误
This commit is contained in:
1 parent
4d92e8e919
commit
82da4d8bb5
8 files changed
+134
-29
No files matched your search
@@ -131,7 +131,8 @@ app shell / routes
|
||||
- 已完成阶段 3 第一个 PR 切片“HTTP 错误结构盘点与第一批契约测试”:新增共享 `httpapi.ErrorResponse`,统一 `code`/`message`/`request_id` 错误边界;认证失败改用 401 和稳定 `authentication_failed`,健康检查和账号列表改用具名 DTO;React 请求层移除 `detail/msg` 错误依赖并为账号列表补充具名类型;新增健康检查、认证失败和账号列表契约测试,Go/React 全量门禁通过并合并为一个可回滚提交;
|
||||
- 已完成阶段 3 第二个 PR 切片“剩余认证与公共 API 错误迁移”:初始化冲突、管理员/用户密码修改、登录凭据校验、用户名冲突、公开设置故障和 SPA API 404 均返回统一错误 DTO 与正确状态码;新增状态码/错误码契约测试,Go 全量门禁通过并合并为一个可回滚提交;
|
||||
- 已完成阶段 3 第三个 PR 切片“订单与账号业务 API 错误响应迁移”:订单刷新、手动发货和订单导入不再返回顶层 HTTP 200 + `success:false`,批量结果改用 `partial_failure`,刷新明细错误统一使用 `message`;账号任务的 502 错误改用统一错误 DTO;新增订单/账号契约测试并通过全量门禁,逐项结果中的 `success` 仅保留为批处理行状态;
|
||||
- 阶段 3 下一 PR 切片为“聊天、商品与自动化业务 API 错误响应迁移”:继续按业务域批量收敛遗留 `success:false`、`error`/`detail` 响应,不拆分单个 handler 提交;
|
||||
- 已完成阶段 3 第四个 PR 切片“聊天、商品与自动化业务 API 错误响应迁移”:聊天发送失败和商品发布失败均改用统一 `code`/`message`/`request_id` 错误 DTO,商品远端已成功但本地保存失败的恢复信息迁移到可选 `details`;React 错误类型同步支持 `details`,新增 HTTP DTO、聊天/自动化/商品契约测试并通过前端门禁;
|
||||
- 阶段 3 下一 PR 切片为“二维码登录、密码登录和剩余公共业务错误响应迁移”:继续收敛遗留 HTTP 200 + `success:false` 及动态错误别名,不拆分单个 handler 提交;
|
||||
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
|
||||
|
||||
## 6. 阶段 0:治理文档与强约束
|
||||
@@ -511,3 +512,4 @@ npm --prefix frontend run build
|
||||
| 2026-08-14 | 完成阶段 3 第一个 PR 切片“HTTP 错误结构盘点与第一批契约测试” | 共享错误 DTO、认证 401、健康检查和账号列表具名 DTO 已落地;React 请求层完成错误契约迁移;Go/React 全量测试、vet、lint、注释和前端构建通过 | 阶段 3:剩余认证与公共 API 错误迁移 |
|
||||
| 2026-08-14 | 完成阶段 3 第二个 PR 切片“剩余认证与公共 API 错误迁移” | 初始化、密码修改、凭据校验、用户名冲突、公开设置故障和 SPA API 404 的状态码/错误码契约已统一;契约测试、全量测试、vet、lint、注释和 diff 门禁通过 | 阶段 3:订单与账号业务 API 错误响应迁移 |
|
||||
| 2026-08-14 | 完成阶段 3 第三个 PR 切片“订单与账号业务 API 错误响应迁移” | 订单批量接口移除顶层 HTTP 200 + `success:false`,逐项失败保留行级状态并统一为 `message`;账号任务 502 改用统一错误 DTO;订单/账号契约测试、全量测试、race、vet、lint、注释和 diff 门禁通过 | 阶段 3:聊天、商品与自动化业务 API 错误响应迁移 |
|
||||
| 2026-08-14 | 完成阶段 3 第四个 PR 切片“聊天、商品与自动化业务 API 错误响应迁移” | 聊天发送和商品发布失败统一为 `code`/`message`/`request_id`,远端发布后的商品核对信息迁移到 `details`;React 错误类型、HTTP DTO 测试和业务契约测试已更新;前端类型检查、测试、构建及 Go 注释门禁通过 | 阶段 3:二维码登录、密码登录和剩余公共业务错误响应迁移 |
|
||||
@@ -352,6 +352,8 @@ export interface ApiErrorResponse {
|
||||
message: string;
|
||||
/** 可选的服务端请求追踪标识。 */
|
||||
request_id?: string;
|
||||
/** 仅供恢复或审计使用的结构化附加信息。 */
|
||||
details?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** 账号列表接口返回的非敏感具名 DTO。 */
|
||||
|
||||
@@ -37,6 +37,8 @@ type ErrorResponse struct {
|
||||
Message string `json:"message"`
|
||||
// RequestID 是可选的请求追踪标识,便于服务端日志关联。
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
// Details 是仅供恢复或审计使用的结构化附加信息,不承载错误判定逻辑。
|
||||
Details map[string]any `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
// CodeForStatus 将 HTTP 状态码映射为稳定的通用错误码。
|
||||
@@ -67,8 +69,13 @@ func CodeForStatus(status int) string {
|
||||
|
||||
// WriteError 使用统一的 code、message 和可选 request_id 写入 JSON 错误响应。
|
||||
func WriteError(w http.ResponseWriter, status int, code, message, requestID string) {
|
||||
WriteErrorDetails(w, status, code, message, requestID, nil)
|
||||
}
|
||||
|
||||
// WriteErrorDetails 使用统一错误字段和可选附加详情写入 JSON 错误响应。
|
||||
func WriteErrorDetails(w http.ResponseWriter, status int, code, message, requestID string, details map[string]any) {
|
||||
// response 是本次请求要序列化的统一错误 DTO。
|
||||
response := ErrorResponse{Code: code, Message: message, RequestID: requestID}
|
||||
response := ErrorResponse{Code: code, Message: message, RequestID: requestID, Details: details}
|
||||
if response.Code == "" {
|
||||
response.Code = CodeForStatus(status)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestWriteErrorDetails 验证统一错误 DTO 可携带恢复所需的结构化详情。
|
||||
func TestWriteErrorDetails(t *testing.T) {
|
||||
// recorder 是捕获错误响应的测试记录器。
|
||||
recorder := httptest.NewRecorder()
|
||||
// details 是远端操作完成后供客户端核对的商品信息。
|
||||
details := map[string]any{"item_id": "remote-item", "item_url": "https://example/item/remote-item"}
|
||||
WriteErrorDetails(recorder, http.StatusInternalServerError, "remote_published_local_save_failed", "本地保存失败", "req-1", details)
|
||||
if recorder.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
// response 是反序列化后的统一错误 DTO。
|
||||
var response ErrorResponse
|
||||
// decodeErr 表示错误响应 JSON 反序列化失败的原因。
|
||||
if decodeErr := json.Unmarshal(recorder.Body.Bytes(), &response); decodeErr != nil {
|
||||
t.Fatalf("decode error response: %v", decodeErr)
|
||||
}
|
||||
if response.Code != "remote_published_local_save_failed" || response.Message != "本地保存失败" || response.RequestID != "req-1" {
|
||||
t.Fatalf("response=%+v", response)
|
||||
}
|
||||
if response.Details["item_id"] != "remote-item" || response.Details["item_url"] != "https://example/item/remote-item" {
|
||||
t.Fatalf("details=%+v", response.Details)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/httpapi"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
// TestAPIContractChatAutomationAndItemErrors 验证聊天、自动化和商品失败均返回统一错误 DTO。
|
||||
func TestAPIContractChatAutomationAndItemErrors(t *testing.T) {
|
||||
// srv 是用于验证聊天、自动化和商品错误契约的 HTTP 测试服务。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// srv.MTop 是返回缺少商品 ID 结果的测试平台客户端。
|
||||
srv.MTop = &stubPublishMTop{publish: func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
|
||||
return &mtop.PublishItemResult{Title: "测试商品"}, nil
|
||||
}}
|
||||
// handler 是当前测试使用的完整路由树。
|
||||
handler := srv.Router()
|
||||
// sessionCookie 是管理员登录后得到的认证会话。
|
||||
sessionCookie := loginHelper(t, handler)
|
||||
assertUnifiedAPIError(t, handler, http.MethodPost, "/api/chat/messages", `{}`, sessionCookie, http.StatusServiceUnavailable, httpapi.CodeServiceUnavailable, "聊天服务未启用", false)
|
||||
assertUnifiedAPIError(t, handler, http.MethodPost, "/api/account-tasks/acc1/run", `{"task_type":"auto_rate"}`, sessionCookie, http.StatusServiceUnavailable, httpapi.CodeServiceUnavailable, "自动化中心未启用", false)
|
||||
// body 和 contentType 是有效商品发布表单及其 multipart 类型。
|
||||
body, contentType := buildPublishMultipart(t, map[string]string{"cookie_id": "acc1", "title": "测试商品", "price": "12.50", "quantity": "1"})
|
||||
// req 是触发远端结果缺少商品 ID 的发布请求。
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish", body)
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
req.AddCookie(sessionCookie)
|
||||
// recorder 是捕获商品发布错误响应的测试记录器。
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, req)
|
||||
if recorder.Code != http.StatusBadGateway {
|
||||
t.Fatalf("publish status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
// response 是商品发布失败的统一错误 DTO。
|
||||
var response httpapi.ErrorResponse
|
||||
// decodeErr 表示商品发布错误响应 JSON 反序列化失败的原因。
|
||||
if decodeErr := json.Unmarshal(recorder.Body.Bytes(), &response); decodeErr != nil {
|
||||
t.Fatalf("decode publish error: %v", decodeErr)
|
||||
}
|
||||
if response.Code != "publish_result_missing_item_id" || response.Message == "" {
|
||||
t.Fatalf("response=%+v", response)
|
||||
}
|
||||
if response.Details != nil {
|
||||
t.Fatalf("unexpected details=%+v", response.Details)
|
||||
}
|
||||
if strings.Contains(recorder.Body.String(), `"success"`) {
|
||||
t.Fatalf("publish error contains legacy success field: %s", recorder.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -91,6 +91,11 @@ func writeErrCode(w http.ResponseWriter, status int, code, msg, requestID string
|
||||
httpapi.WriteError(w, status, code, msg, requestID)
|
||||
}
|
||||
|
||||
// writeErrDetails 写带恢复信息的统一错误响应,详情只作为附加数据返回。
|
||||
func writeErrDetails(w http.ResponseWriter, status int, code, msg, requestID string, details map[string]any) {
|
||||
httpapi.WriteErrorDetails(w, status, code, msg, requestID, details)
|
||||
}
|
||||
|
||||
// writeCredentialVerificationError 将当前密码校验失败区分为认证失败或内部故障。
|
||||
func writeCredentialVerificationError(w http.ResponseWriter, err error) {
|
||||
if errors.Is(err, db.ErrPasswordMismatch) {
|
||||
|
||||
@@ -207,7 +207,7 @@ func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
if err := sender.SendImage(engine.WithOutgoingMessageKey(r.Context(), message.MessageKey), chatID, buyerID, upload.URL, 0); err != nil {
|
||||
failed, _ := s.chat.SetOutgoingStatus(context.Background(), accountID, message.MessageKey, "failed")
|
||||
writeJSON(w, http.StatusBadGateway, map[string]any{"message": failed, "error": "图片发送失败,请重试"})
|
||||
writeErrDetails(w, http.StatusBadGateway, "chat_image_send_failed", "图片发送失败,请重试", "", map[string]any{"outgoing_message": failed})
|
||||
return
|
||||
}
|
||||
sent, err := s.chat.SetOutgoingStatus(r.Context(), accountID, message.MessageKey, "sent")
|
||||
@@ -354,7 +354,7 @@ func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) {
|
||||
sendContext := engine.WithOutgoingMessageKey(r.Context(), message.MessageKey)
|
||||
if err := sender.SendText(sendContext, input.ChatID, input.BuyerID, input.Text); err != nil {
|
||||
failed, _ := s.chat.SetOutgoingStatus(context.Background(), input.AccountID, message.MessageKey, "failed")
|
||||
writeJSON(w, http.StatusBadGateway, map[string]any{"message": failed, "error": "发送失败,请重试"})
|
||||
writeErrDetails(w, http.StatusBadGateway, "chat_message_send_failed", "发送失败,请重试", "", map[string]any{"outgoing_message": failed})
|
||||
return
|
||||
}
|
||||
sent, err := s.chat.SetOutgoingStatus(r.Context(), input.AccountID, message.MessageKey, "sent")
|
||||
|
||||
@@ -160,23 +160,23 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
status = http.StatusForbidden
|
||||
msg = "该账号没有库存发布权限,无法按库存数量发布商品"
|
||||
}
|
||||
writeJSON(w, status, map[string]any{
|
||||
"success": false,
|
||||
"code": perr.Code,
|
||||
"message": msg,
|
||||
"ret": perr.Ret,
|
||||
})
|
||||
writeErrCode(
|
||||
w,
|
||||
status,
|
||||
string(perr.Code),
|
||||
msg,
|
||||
"")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusBadGateway, callErr.Error())
|
||||
return
|
||||
}
|
||||
if res == nil || strings.TrimSpace(res.ItemID) == "" {
|
||||
writeJSON(w, http.StatusBadGateway, map[string]any{
|
||||
"success": false,
|
||||
"code": "publish_result_missing_item_id",
|
||||
"message": "平台返回发布成功,但缺少商品 ID,无法确认发布结果",
|
||||
})
|
||||
writeErrCode(w, http.StatusBadGateway,
|
||||
"publish_result_missing_item_id",
|
||||
"平台返回发布成功,但缺少商品 ID,无法确认发布结果",
|
||||
"",
|
||||
)
|
||||
return
|
||||
}
|
||||
detail := map[string]any{
|
||||
@@ -200,23 +200,23 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Error("平台已发布但保存本地商品失败", "cookie_id", cookieID, "item_id", res.ItemID, "err", err)
|
||||
}
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]any{
|
||||
"success": false,
|
||||
"code": "remote_published_local_save_failed",
|
||||
"message": "商品已在平台发布,但本地保存失败,请勿重复发布并根据商品 ID 人工核对",
|
||||
"item_id": res.ItemID,
|
||||
"item_url": res.ItemURL,
|
||||
})
|
||||
writeErrDetails(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
"remote_published_local_save_failed",
|
||||
"商品已在平台发布,但本地保存失败,请勿重复发布并根据商品 ID 人工核对",
|
||||
"",
|
||||
map[string]any{"item_id": res.ItemID, "item_url": res.ItemURL})
|
||||
return
|
||||
}
|
||||
if responseCookieErr != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]any{
|
||||
"success": false,
|
||||
"code": "remote_published_cookie_save_failed",
|
||||
"message": "商品已在平台发布并保存到本地,但登录凭证更新保存失败,请勿重复发布并尽快重新登录",
|
||||
"item_id": res.ItemID,
|
||||
"item_url": res.ItemURL,
|
||||
})
|
||||
writeErrDetails(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
"remote_published_cookie_save_failed",
|
||||
"商品已在平台发布并保存到本地,但登录凭证更新保存失败,请勿重复发布并尽快重新登录",
|
||||
"",
|
||||
map[string]any{"item_id": res.ItemID, "item_url": res.ItemURL})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
|
||||
Reference in new issue
Block a user