API契约:迁移聊天商品与自动化错误
This commit is contained in:
1 parent
4d92e8e919
commit
82da4d8bb5
8 files changed
+134
-29
No files matched your search
@@ -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